从具有已创建属性的子对象访问父对象的JavaScript
以下代码可以完美地工作:从具有已创建属性的子对象访问父对象的JavaScript,javascript,inheritance,prototype,Javascript,Inheritance,Prototype,以下代码可以完美地工作: function Shape(){} Shape.prototype.name = 'Shape'; Shape.prototype.toString = function(){ return this.constructor.parent ? this.constructor.parent.toString() + ',' + this.name : this.name;
function Shape(){}
Shape.prototype.name = 'Shape';
Shape.prototype.toString = function(){
return this.constructor.parent
? this.constructor.parent.toString() + ',' + this.name
: this.name;
};
function TwoDShape(){}
var F = function(){};
F.prototype = Shape.prototype;
TwoDShape.prototype = new F();
TwoDShape.prototype.constructor = TwoDShape;
TwoDShape.parent = Shape.prototype;
TwoDShape.prototype.name = '2D Shape';
var my = new TwoDShape();
console.log(my.toString());
它打印出以下内容:形状,2D形状
然而,有人能解释一下下面的事实吗
返回this.constructor.parent(我已经将它从uber改为parent,这更有意义)在我看来,调用原型对象而不是实例上的方法是一个非常糟糕的主意。你从哪里得到的代码?请注意,
返回this.constructor.parent
本身不是一个语句,而是this.constructor.parent
是中的条件。我从Stoyan Stefanov和Kumar Chetan Sharma的新书《面向对象javascript》中得到了这段代码