日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

es6中的类及es5类的实现

發布時間:2023/12/2 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 es6中的类及es5类的实现 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

目錄

  • 類的特點

類的特點

1.類只能通過new得到

在es6中類的使用只能是通過new,如果你將它作為一個函數執行,將會報錯。

//es6的寫法 class Child {constructor() {this.name = 1;} } let child = new Child(); console.log(child.name)//1 //如果直接方法調用的形式,會報錯 let child = Child();//Class constructor Child cannot be invoked without 'new'

es5中的class其實就是一個方法,沒有關鍵字class

//es5中類的寫法,但是這樣直接用方法名調用并不會報錯 var Person = (function () {function Person(name) {this.name = name;}Person.prototype.SayHello = function () {window.alert("My name is " + this.name + ".");};return Person; })(); var p = Person()//不報錯

為了實現類似于es6中的調用檢查,我們需要自己手寫一個調用檢查的函數。這個函數的原理就是用當前的this和構造函數進行比較,如果這個this指向的window,那么可以看出是用通過方法名直接調用的,如果this是構造函數那么就是通過new得到的

var Person = (function () { //類的調用檢測function _classCheck(instance, constructor) {if (!(instance instanceof constructor)) {throw new Error('Class constructor Child cannot be invoked without new')}}function Person(name) {this.name = name;_classCheck(this, Person)}Person.prototype.SayHello = function () {window.alert("My name is " + this.name + ".");};return Person; })(); var p = Person()

子類會繼承父類的公有屬性和靜態方法

es6中的寫法

//es6中的寫法 class Child extends Person {constructor() {super()this.name = 1;} } //es5中的寫法 var Clild = (function (Person) { //類的調用檢測function _classCheck(instance, constructor) {if (!(instance instanceof constructor)) {throw new Error('Class constructor Child cannot be invoked without new')}} //子類繼承父類的方法function _inherins(subclass, superclass) {subclass.prototype = Object.create(superclass.prototype, { constructor: { value: subclass } })Object.setPrototypeOf(subclass, superclass)}_inherins(Clild, Person)function Clild() {let obj=Person.call(this)//子類繼承私有屬性let that=this;if(typeof obj=='object'){that=obj}that.name=1;//解決了父類是引用類型的問題_classCheck(this, Clild)return that} return Clild; })(Person);

轉載于:https://www.cnblogs.com/hanqingtao/p/9957043.html

總結

以上是生活随笔為你收集整理的es6中的类及es5类的实现的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。