3
私はjavascriptで 'classes'を操作する方法を学びたいと思っています。Javascriptクラス継承
function Shape(x, y) {
this.x= x;
this.y= y;
}
Shape.prototype.toString= function() {
return 'Shape at '+this.x+', '+this.y;
};
function Circle(x, y, r) {
Shape.call(this, x, y); // invoke the base class's constructor function to take co-ords
this.r= r;
}
Circle.prototype= $.extend(true, {}, Shape.prototype);
Circle.prototype.toString= function() {
return 'Circular '+Shape.prototype.toString.call(this)+' with radius '+this.r;
}
var c = new Circle(1,2,3);
alert(c);
はそれのコンストラクタの内部で形状のtoString関数を定義する方法はありますか、それはこのような状況では意味がありません。ここで
は私のコードですか?
この場合、 'this.toString = function(){...}'は機能しませんか? – Connell
いいえ、そうではありません。相違点を参照してください。 http://jsfiddle.net/paptamas/qDSkj/ および http://jsfiddle.net/paptamas/cbnLB/ –
プロトタイプは正しい方法です。一度toString関数を作成します。コンストラクタでは、新しいものごとに作成されます。 – Joe