You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
JavaScript相比于其他面向类的语言,在实现继承时并没有真正对构造类进行复制,当我们使用var children = new Parent()继承父类时,我们理所当然的理解为children ”为parent所构造“。实际上这是一种错误的理解。严格来说,JS才是真正的面向对象语言,而不是面向类语言。它所实现的继承,都是通过每个对象创建之初就存在的prototype属性进行关联、委托,从而建立练习,间接的实现继承,实际上不会复制父类。
ES5最常见的两种继承:原型链继承、构造函数继承
1.原型链继承
// 定义父类
function Parent(name) {
this.name = name;
}
Parent.prototype.getName = function() {
return this.name;
};
// 定义子类
function Children() {
this.age = 24;
}
// 通过Children的prototype属性和Parent进行关联继承
Children.prototype = new Parent('陈先生');
// Children.prototype.constructor === Parent.prototype.constructor = Parent
var test = new Children();
// test.constructor === Children.prototype.constructor === Parent
test.age // 23
test.getName(); // 陈先生
// 定义父类
class Father {
constructor(name, age) {
this.name = name;
this.age = age;
}
show() {
console.log(`我叫:${this.name}, 今年${this.age}岁`);
}
};
// 通过extends关键字实现继承
class Son extends Father {};
let son = new Son('陈先生', 3000);
son.show(); // 我叫陈先生 今年3000岁
JavaScript相比于其他面向类的语言,在实现继承时并没有真正对构造类进行复制,当我们使用
var children = new Parent()
继承父类时,我们理所当然的理解为children ”为parent所构造“。实际上这是一种错误的理解。严格来说,JS才是真正的面向对象语言,而不是面向类语言。它所实现的继承,都是通过每个对象创建之初就存在的prototype属性进行关联、委托,从而建立练习,间接的实现继承,实际上不会复制父类。1.原型链继承
我们可以发现,整个继承过程,都是通过原型链之间的指向进行委托关联,直到最后形成了”由构造函数所构造“的结局。
2.构造函数继承
构造继承关键在于,通过在子类的内部调用父类,即通过使用apply()或call()方法可以在将来新创建的对象上获取父类的成员和方法。
ES6中新增了class关键字来定义类,通过保留的关键字extends实现了继承。实际上这些关键字只是一些语法糖,底层实现还是通过原型链之间的委托关联关系实现继承。
区别于ES5的继承,ES6的继承实现在于使用super关键字调用父类,反观ES5是通过call或者apply回调方法调用父类。
The text was updated successfully, but these errors were encountered: