ES5 定義構(gòu)造函數(shù)
通過構(gòu)造函數(shù)加屬性丈钙,通過原型加方法:
function MathHandle(x, y) {
this.x = x;
this.y = y;
}
MathHandle.prototype.add = function() {
return this.x + this.y;
}
var m = new MathHandle(1, 2);
console.log(m.add()); // 3
ES6 Class語法
class MathHandle {
constructor(x, y) {
this.x = x;
this.y = y;
}
add() {
return this.x + this.y;
}
}
var m = new MathHandle(1, 2);
console.log(m.add()); // 3
class 實際上是語法糖,編譯后就是ES5中的構(gòu)造函數(shù):
typeof MathHandle; // function
MathHandle === MathHandle.prototype.constructor; // true
m.__proto__ === MathHandle.prototype // true
實例的隱式原型 = 構(gòu)造函數(shù)的顯式原型
ES5 繼承
將低級構(gòu)造函數(shù)的原型賦值為高級構(gòu)造函數(shù)的實例來實現(xiàn)繼承:
// 動物
function Animal() {
this.eat = function () {
alert('Animal eat')
}
}
// 狗
function Dog() {
this.bark = function () {
alert('Dog bark')
}
}
// 綁定原型胸懈,實現(xiàn)繼承
Dog.prototype = new Animal()
var hashiqi = new Dog()
hashiqi.bark()
hashiqi.eat()
ES6 class 繼承
通過 extends
關(guān)鍵字和 super
方法實現(xiàn)繼承:
class Animal {
constructor(name) {
this.name = name;
}
eat() {
console.log(`${this.name} eat`);
}
}
class Dog extends Animal {
constructor(name) {
super(name);
this.name = name;
}
say() {
console.log(`${this.name} say`);
}
}
const hashiqi = new Dog("哈士奇");
hashiqi.eat();
hashiqi.say();
本質(zhì)還是語法糖担扑,使用 prototype。