javascript高级程序设计阅读收获(8.3.1)——原型链
·
1.默认原型
function Aaa(){
this.property = true;
}
Aaa.prototype.getAaaValue = function(){
return this.property;
}
function Bbb(){
this.Bbbproperty = false;
}
Bbb.prototype = new Aaa();
Bbb.prototype.getBbbValue = function(){
return this.Bbbproperty;
}
let instance = new Bbb();
console.log(instance.getBbbValue());//false
- instance的背后的原型链为:instance→Bbb→Aaa→Object。
- 例子中实现继承的关键是Bbb没有使用默认原型,而是将其替换成了Aaa的实例。
- instance实例的[[Prototype]]特性指向了Bbb的原型对象,Bbb的原型对象的[[Prototype]]特性指向了Aaa的原型。
- 任何函数的默认原型都是一个Objcet的实例,这是为什么自定义类型能够继承包裹toString、valueOf在内的所有默认方法的原因。
2.原型与实例关系
function Aaa(){
this.property = true;
}
Aaa.prototype.getAaaValue = function(){
return this.property;
}
function Bbb(){
this.Bbbproperty = false;
}
Bbb.prototype = new Aaa();
Bbb.prototype.getBbbValue = function(){
return this.Bbbproperty;
}
let instance = new Bbb();
console.log(instance instanceof Object);//true
console.log(instance instanceof Aaa);//true
console.log(instance instanceof Bbb);//true
- 从技术上讲,instance是Object、Bbb、Aaa的实例,因为instance的原型链中包含这些构造函数的原型。结果就是instanceof对这些构造函数都返回true。
console.log(Object.prototype.isPrototypeOf(instance));
console.log(Aaa.prototype.isPrototypeOf(instance));
console.log(Bbb.prototype.isPrototypeOf(instance));
- 可以用isPrototypeOf方法来判断原型链中是否包含这个原型。
3.关于方法
function Aaa(){
this.property = true;
}
Aaa.prototype.getAaaValue = function(){
return this.property;
}
function Bbb(){
this.Bbbproperty = false;
}
Bbb.prototype = new Aaa();//原型赋值
Bbb.prototype.getBbbValue = function(){
return this.Bbbproperty;
}
Bbb.prototype.getAaaValue = function(){
return false;
}
let instance = new Bbb();
console.log(instance.getAaaValue());
- 如果要覆盖父类的方法,需要在原型赋值之后再添加到原型上。
function Aaa(){
this.property = true;
}
Aaa.prototype.getAaaValue = function(){
return this.property;
}
function Bbb(){
this.Bbbproperty = false;
}
Bbb.prototype = new Aaa();//原型赋值
Bbb.prototype = {
getBbbValue(){
return this.Bbbproperty;
}
}
let instance = new Bbb();
console.log(instance.getBbbValue());//false
console.log(instance.getAaaValue());//出错
- 以对象字面量方式创建原型方法会破坏之前的原型链。
4.原型链的问题
function Aaa(){
this.numbers= [0,1,2,3];
}
function Bbb(){
this.Bbbproperty = false;
}
Bbb.prototype = new Aaa();//原型赋值
let instance1 = new Bbb();
console.log(instance1.numbers);//[0, 1, 2, 3]
instance1.numbers.push(5);
let instance2 = new Bbb();
console.log(instance1.numbers);//[0, 1, 2, 3, 5]
console.log(instance2.numbers);//[0, 1, 2, 3, 5]
- 原型中的引用值会在所有实例间共享。
- 子类型在实例化时不能给父类型的构造函数传参。
更多推荐



所有评论(0)