類的特點
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);