Javascript如何实现继承?
在 JavaScript 中,实现继承的方式有多种,包括构造继承
、原型继承
、实例继承
和拷贝继承
等。其中,使用构造函数与原型混合方式是较常用和推荐的方式
。
以下是使用构造函数与原型混合方式实现继承的示例代码:
function Parent() {
this.name = 'poetry';
}
function Child() {
this.age = 28;
}
// 使用构造函数继承
Child.prototype = new Parent();
Child.prototype.constructor = Child;
var demo = new Child();
console.log(demo.age); // 输出: 28
console.log(demo.name); // 输出: poetry
console.log(demo.constructor); // 输出: Child
通过将 Child.prototype
设置为 new Parent()
,子类 Child
继承了父类 Parent
的属性和方法。然后,通过手动将 Child.prototype.constructor
设置为 Child
,确保子类的构造函数指向自身。
这样,demo.constructor
的输出将是 Child
,表示 demo
实例的构造函数是 Child
,以确保子类的实例通过 constructor
属性可以准确地识别其构造函数。
THE END
暂无评论内容