书上的解释不太理解,求大神帮解释下。
为什么第一种没有继承到sides属性
// 创建作用域安全的构造函数
function Polygon(sides) {
if (this instanceof Polygon) {
console.log('this', this);
this.sides = sides;
this.getArea = function(){
return 0;
}
} else {
return new Polygon(sides);
}
}
// 非作用域安全的构造函数
function Rectangle(width, height) {
Polygon.call(this, 2);
this.width = width;
this.height = height;
this.getArea = function (){
return this.width * this.height;
}
}
let rect = new Rectangle(5,10);
console.log(rect.sides);
为什么rect没有继承到side属性
而通过原型就可以
Rectangle.prototype = new Polygon();
let rect = new Rectangle(2,4);
console.log(rect.sides);// 2
第一种情况,当你let rect = new Rectangle(5,10);时,此时rect是Rectangle的一个实例,Polygon.call(this, 2); 中this指代rect,你把rect作为Polygon的this来调用Polygon,当在Polygon中判断(this instanceof Polygon)这句话时,发现this也就是rect不是Polygon的实例,根据instanceof的用法它会查找this的原型链,原型链中是否有Polygon的实例,如果找到就返回true。显然没找到,所以实际上Polygon.call(this, 2);这句话相当于执行了new Polygon(2),与rect无关,所以rect中没有sides属性。
第二中情况:Rectangle.prototype = new Polygon();你让Rectangle.prototype变为Polygon的一个实例(这其实是javascript的原型继承),看个例子:
因此第二种情况中Polygon.call(this, 2);它执行的是if语句中的代码,把sides和getArea放到了this中,所以rect.sides会是2。