原型必须是实际的对象。在这种情况下,您应该传递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
找到原型递归,它不会查找形状的原型,因为它不是直接设置,也不是用来创建Rectangle
的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 = 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
我相信你想用'Object.create(Shape.prototype)'代替 – 2013-04-24 15:33:14
不,在我的代码中。我只想找出Object.create(Shape)发生了什么;'谢谢。 – 2013-04-24 15:34:40
当您从链接或文档中读取时仔细阅读。该文件清楚地说 'Rectangle.prototype = Object.create(Shape。原型);' create方法采用原型(不是类名或函数)和返回原型(不是类名或函数)。 – 2013-04-24 15:36:11