【问题标题】:Something about prototype in Javascript关于 Javascript 中的原型
【发布时间】:2018-02-07 11:00:04
【问题描述】:

我编写的Javascript代码如下:

function Shape() {
  this.x = 0;
  this.y = 0;
}
function Rectangle() {
   Shape.call(this); // call super constructor.
}
Rectangle.prototype = Object.create(Shape.prototype);
function Tmp() {
   this.a = 0;
   this.b = 0;
}
Rectangle.prototype.constructor = Tmp;
var rect = Object.create(Rectangle.prototype);
console.log(rect)

那么输出是:

rect应该由构造函数Tmp初始化。我的问题是由构造函数Tmp初始化的对象rect的属性a和b在哪里?

【问题讨论】:

  • 为什么要将Rectangle.prototype.constructor 设置为Tmp?这是一件非常奇怪且具有误导性的事情。

标签: javascript javascript-objects dom-events


【解决方案1】:

rect应该由构造函数Tmp初始化

如果你愿意,你会这样做:

Tmp.call(rect);

...之后

var rect = Object.create(Rectangle.prototype);

function Shape() {
    this.x = 0;
    this.y = 0;
}
function Rectangle() {
     Shape.call(this); // call super constructor.
}
Rectangle.prototype = Object.create(Shape.prototype);
function Tmp() {
   this.a = 0;
   this.b = 0;
}
//Rectangle.prototype.constructor = Tmp;
var rect = Object.create(Rectangle.prototype);
Tmp.call(rect);
console.log(rect);

Object.create 根本不调用任何函数,它只是创建具有给定原型的对象。所以RectangleShapeTmp都不会被var rect = Object.create(Rectangle.prototype);调用。

或者,如果您还希望 Rectangle 完成其工作,请将 Object.create 调用替换为:

var rect = new Rectangle();
Tmp.call(rect);

Rectangle.prototypeconstructor 属性设置为Tmp,而不是Rectangle,这非常奇怪。我强烈建议不要这样做。如果您只需要Tmp 来初始化实例,则无需这样做。 SomeFunction.prototype 引用的对象的constructor 属性应该是SomeFunction,而不是其他任何东西。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-19
    • 2016-05-13
    • 1970-01-01
    • 2018-09-10
    • 1970-01-01
    • 2010-09-27
    • 2018-02-11
    • 2017-02-16
    相关资源
    最近更新 更多