#搞懂还是得自己动手#
原型链
javascript
function Person(name) {
this.name = name;
}
Person.prototype.sayName = function() {
console.log(this.name);
};
const p = new Person("Alice");
原型链关系图:
原型链:person->Person.prototype->Object.prototype->null
继承
利用原型实现继承
组合继承
javascript
function Parent(name) {
this.name = name;
}
Parent.prototype.say = function() {};
function Child(name) {
Parent.call(this, name); // 第1次调用Parent
}
Child.prototype = new Parent(); // 第2次调用Parent(导致Child.prototype冗余属性)
子类创建一次,父类构造函数需执行两次
寄生组合继承
javascript
function inheritPrototype(Child, Parent) {
const prototype = Object.create(Parent.prototype); // 创建父类原型副本(避免直接引用)
prototype.constructor = Child; // 修正constructor指向
Child.prototype = prototype;
}
// 父类
function Parent(name) {
this.name = name;
}
Parent.prototype.say = function() {};
// 子类
function Child(name, age) {
Parent.call(this, name); // 仅调用一次父类构造函数
this.age = age;
}
// 继承原型方法
inheritPrototype(Child, Parent);
// 子类新增方法
Child.prototype.run = function() {};
- 仅调用一次父类构造函数
- 子类原型链纯净,无冗余属性
- 创建中间对象,增加内存开销