先看一段代码
function a(){
this.number = 1;
}
a.prototype.number = 2;
a.prototype.print = function(){
console.log(this.number);
}
function b(){
a.call(this);
}
b.prototype = Object.create(a.prototype);
var c = new b();
c.print();
这段代码中,我定义了两个类a,b,b继承a类的属性和方法。那b继承的是number是等于1还是等于2呢?
答案是1。
因为原型链的属性添加相当于从别的地方继承了属性,当自己里面有重名属性时“继承”的属性就会被掩盖(但依然存在,可以通过this.__proto__.number获取),同样道理,如果是在原型链上添加的方法与公有方法重名也是优先调用公有方法,同时亦可从__proto__中获取原型链的方法。
当然,如果没有重名属性的话(去掉this.number),结果就是原型链上的属性被调用(number = 2).
还有就是a.call(this)可以写在外面( a.call(b) 吗?
不能,在this指的是obj对象,而b指的是类(function),而再深入一点的情况我抽空再研究。