本文中,proto === [[Prototype]]
基本思想:
function Super() {};
function Sub() {};
Super.prototype.sayHi = function () { console.log('hi') };
Sub.prototype = new Super();
const supInstance1 = new Sub();
supInstance1.sayHi(); // hi
缺点
基本思想
function Car(wheels) {
this.wheels = wheels;
}
function ElectricCar(wheels, type) {
Cat.call(this, wheels);
this.type = type;
}
缺点
基本思想
function Super(title) {
this.title = title;
}
Super.prototype.sayHi = function () {
console.log(this.title, " <- Super title");
};
function Sub(superTitle, subTitle) {
Super.call(this, superTitle);
this.subTitlte = subTitle;
}
Sub.prototype = new Super();
const subInstance = new Sub("superTitle in instance", "subTitle in instance");
subInstance.sayHi(); // ****subtitle in instance <- this title****
/* subInstance结构类型
**{
"title": "superTitle in instance",
"subTitlte": "subTitle in instance",
[[Prototype]]: Super
}
--- 在[[Prototype]]:Super中
--- Super的结构类型
{
title: undefined,
[[Prototype]]: Object,
}**
*/
缺点
基本思想
对象间构造原型链实现属性的共享。
实现
es5的Object.create函数
// 返回一个对象,对象.__proto__ 指向 o
function objectCreate(o) {
function F() {};
F.prototype = o;
return new F();
}
基本思想
function createSub(originObject) {
const newObject = Object.create(originObject);
newObject.sayHi = function() { console.log('hi') };
return newObject;
}
const person = {
name: '张三',
friends: ['李四', '赵武', '甲一']
};
const personA = createSub(person);
personA.sayHi();
优缺点
???感觉没有使用的场景
基本思想
function Super(name) {
this.name = name;
}
Super.prototype.sayHi = function() { console.log(`hi this is super and name is ${this.name}`)};
function Sub(name, age) {
Super.call(this, name);
this.age = age;
}
Sub.prototype = Object.create(Super.prototype, {
constructor: {
value: Sub,
enumerable: false,
writable: true,
configurable: true,
},
});
// 这里同样可以用es6中的 setPrototypeOf 来设置原型链的链接
Sub.prototype.sayAge = function () { console.log(`the age of ${this.name} is ${this.age}`); }
const subInstance = new Sub('Sub instance', 12);
subInstance.sayHi(); // hi this is super and name is Sub instance
subInstance.sayAge(); // **the age of Sub instance is 12**
优缺点
es6的继承本质上是es5继承的语法糖。
// 可以实现和寄生式组合继承完全相同的效果
class Super {
constructor(name) {
this.name = name;
}
sayHi() {
console.log(`hi this is super and name is ${this.name}`)
}
}
class Sub extends Super {
constructor(name, age) {
super(name);
this.age = age;
}
sayAge() {
console.log(`the age of ${this.name} is ${this.age}`)
}
}
const subInstance = new Sub('Sub instance', 12);
subInstance.sayHi(); // hi this is super and name is Sub instance
subInstance.sayAge(); // **the age of Sub instance is 12**
参考数据:
- [1] [你不知道的JavaScript]
- [2] [JavaScript高级程序设计]
- [3] [[mdn](https://developer.mozilla.org/)](https://developer.mozilla.org/)