プロトタイプは実際のオブジェクトでなければなりません。この場合、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
を検索し、再帰的にプロトタイプを見つけるため、直接設定されておらず、new
作成にコンストラクターが使用されていないため、Shape のプロトタイプを検索しません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