原生 js (ES5) 实现继承的方式 6 种方式:
- 1、通过原型链继承
- 2、借用构造函数继承
- 3、组合继承
- 4、原型式继承
- 5、寄生式继承
- 6、寄生式组合继承
new 操作符的作用:
- 1、 在内存中创建一个新对象
- 2、这个新对象内部的[[Prototype]]指针被赋值为构造函数的 prototype 属性
- 3、构造函数内部的 this 被赋值为这个新对象(即 this 指向新对象)
- 4、执行构造函数内部的代码(给新对象添加属性)
- 5、如果构造函数返回非空对象,则返回该对象;否则,返回刚创建的新对象
1、通过原型链继承:
function SuperType() {
this.colors = ['red', 'blue', 'green']
}
function SubType() { }
SubType.prototype = new SuperType()
let instance1 = new SubType()
instance1.colors.push('black')
console.log(instance1.colors)
let instance2 = new SubType()
console.log(instance2.colors)
2、借用构造函数继承
function SuperType(name) {
this.name = name
}
function SubType(name1) {
SuperType.call(this, name1)
this.age = 28
}
let instance1 = new SubType('测试名称')
console.log(instance1.name)
console.log(instance1.age)
3、组合式继承
function SuperType(name) {
this.name = name;
this.colors = ["red", "blue", "green"];
}
SuperType.prototype.sayName = function () {
console.log(this.name);
};
function SubType(name, age) {
SuperType.call(this, name);
this.age = age;
}
SubType.prototype = new SuperType();
SubType.prototype.constructor = SubType;
SubType.prototype.sayAge = function () {
console.log(this.age);
};
let instance1 = new SubType("Nicholas", 29);
instance1.colors.push("black");
console.log(instance1.colors);
instance1.sayName();
instance1.sayAge();
let instance2 = new SubType("Greg", 27);
console.log(instance2.colors);
instance2.sayName();
instance2.sayAge();
4、原型式继承
function object(o) {
function F() { }
F.prototype = o
return new F()
}
let person = {
name: "Nicholas",
friends: ["Shelby", "Court", "Van"]
};
let anotherPerson = object(person);
anotherPerson.name = "Greg";
anotherPerson.friends.push("Rob");
let yetAnotherPerson = object(person);
yetAnotherPerson.name = "Linda";
yetAnotherPerson.friends.push("Barbie");
console.log(person.friends);
5、寄生式继承
function createAnother(original) {
let clone = object(original);
clone.sayHi = function () {
console.log("hi");
};
return clone;
}
let person = {
name: "Nicholas",
friends: ["Shelby", "Court", "Van"]
};
let anotherPerson = createAnother(person);
anotherPerson.sayHi();
6、寄生式组合继承
function SuperType(name) {
this.name = name;
this.colors = ["red", "blue", "green"];
}
SuperType.prototype.sayName = function () {
console.log(this.name);
};
function SubType(name, age) {
SuperType.call(this, name);
this.age = age;
}
inheritPrototype(SubType, SuperType);
SubType.prototype.sayAge = function () {
console.log(this.age);
};
总结:常用继承方式使用组合式继承、寄生式组合继承,具体场景具体使用