原型必须是一个实际的对象。在这种情况下,您应该传递 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