0

阅读Object.create文档后。我为它做了一些测试。这是我的代码。请审查它。

function Shape() {
  this.x = 0;
  this.y = 0;
}

Shape.prototype.move = function(x, y) {
    this.x += x;
    this.y += y;
    console.info("Shape moved.");
};

Rectangle=Object.create(Shape);

Rectangle.move(); //?? why move function is not found ?

正如文档所说,Object.create(proto[,propertiesObject]); proto应该是新创建对象的原型。所以,Rectangle.prototype应该等于Shape. 但实际上并非如此。显然我不明白这部分文件。我仍然发现Rectangle.__proto__==Shape是真的。OK,EvenRectangle.__proto__==Shape是真的,为什么Rectangle找不到move函数?move函数不在原型链中吗?我以为move函数在Rectangle.__proto__.prototype,它应该在链中找到。为什么不能?谢谢。

4

2 回答 2

3

原型必须是一个实际的对象。在这种情况下,您应该传递 Shape 的原型,而不是 Shape 函数。

function Shape() {
  this.x = 0;
  this.y = 0;
}

Shape.prototype.move = function(x, y) {
    this.x += x;
    this.y += y;
    console.info("Shape moved.");
};

Rectangle=Object.create(Shape.prototype, {a:1});

Rectangle.move(); // it will call now
Rectangle.a; // 1
Rectangle.x; // NaN ???
Rectangle.y; // NaN ???

请注意,Object.create()这与使用new关键字不同 - 这可能是您正在寻找的东西。

function Shape() {
  this.x = 0;
  this.y = 0;
}

Shape.prototype.move = function(x, y) {
    this.x += x;
    this.y += y;
    console.info("Shape moved.");
};

Rectangle=new Shape;

Rectangle.move(1,2); // works properly now
Rectangle.a; // undefined, we never made one
Rectangle.x; // 1
Rectangle.y; // 2

由于 Javascript 实际上查找构造函数并.prototype递归地查找原型,因此它不会查找 Shape 的原型,因为它不是直接设置的,也不是new用于创建的构造函数Rectangle

function Shape() {
  this.x = 0;
  this.y = 0;
}

Shape.prototype.move = function(x, y) {
    this.x += x;
    this.y += y;
    console.info("Shape moved.");
};

Rectangle = Object.create(Shape);
Rectangle.constructor; // Function()
Rectangle.constructor.prototype; // That's Function.prototype
/* as you can see Shape.prototype is never touched by the prototype chain */

Rectangle.__proto__; // Shape(), not the prototype (doesn't have any direct properties on it)

Rectangle.move(1,2); // TypeError: Rectangle.move is not a function
Rectangle.a; // does not exist
Rectangle.x; // function never called on Rectangle, so also doesn't exist
Rectangle.y; // function never called on Rectangle, so also doesn't exist
于 2013-04-24T15:33:11.453 回答
2

也许这会帮助您了解更多:

https://www.youtube.com/watch?v=DwYPG6vreJg&feature=player_detailpage#t=739s

在这里他解释说它不像你说的那样工作。你的论点

我以为move功能在Rectangle.__proto__.prototype

是正确的。您可以找到moveasRectangle.__proto__.prototype.move但这并不意味着您可以找到它 as Rectangle.move。原型链中断。我认为视频中对此进行了详细描述。

试着想想这些代码部分:

function Shape() {
    this.x = 0;
    this.y = 0;
}

Shape.__proto__.move = function(x, y) {
    this.x += x;
    this.y += y;
    console.info("Shape moved.");
};

Rectangle=Object.create(Shape);

Rectangle.move();

或者:

function Shape() {
    this.x = 0;
    this.y = 0;
}

Shape.prototype.move = function(x, y) {
    this.x += x;
    this.y += y;
    console.info("Shape moved.");
};

Rectangle=Object.create(Shape);

Rectangle.prototype.move();

(在这些情况下,x 和 y 仍然不正确,但您并没有询问它们;))

于 2013-04-29T17:34:10.387 回答