原型必須是實際的對象。在這種情況下,您應該傳遞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