私は、JavaScriptの継承を手に入れようとしています。私のコード例は次のように開始:Javascriptコンストラクタは「サブクラス」の正しい表記法で機能しますか?
var example = example || {};
example.Classes = {};
(function() {
var example = example || {};
example.Classes = {};
var privateVar = 25;
function Superclass() {
this.x = privateVar;
}
Superclass.prototype = {
move: function(x){
this.x += x;
console.log("Superclass move",this.x);
},
dance: function(x){
this.x += x*2;
}
};
function Subclass() {
Superclass.apply(this, arguments);
this.y = 0;
};
Subclass.prototype = Object.create(Superclass.prototype);
Subclass.prototype.constructor = Subclass;
これは成功の継続である:
Subclass.prototype.dance = function(x, y) {
this.x -= (x + privateVar);
this.y -= y;
console.log("Subclass dance", this.x, this.y)
};
example.Classes.Superclass = Superclass;
example.Classes.Subclass = Subclass;
window.example.Classes = example.Classes;
}());
var success = new example.Classes.Subclass();
success.dance(5,4);
success.move(6);
コンソール出力:サブクラスダンス-5 -4
コンソール出力:スーパームーブ1
そして今、失敗した継続 - ここで何が間違っていますか?サブクラスのコンストラクタ関数を書くこの方法を使用できないのはなぜですか?
Subclass.prototype = {
dance: function(x, y) {
this.x -= (x + privateVar);
this.y -= y;
console.log("Subclass dance", this.x, this.y)
}
};
example.Classes.Superclass = Superclass;
example.Classes.Subclass = Subclass;
window.example.Classes = example.Classes;
}());
var failure = new example.Classes.Subclass();
failure.dance(5,4);
failure.move(6);
コンソール出力:サブクラスダンス-5 -4
コンソール出力:ERROR:あなたがオンにするために使用されるオブジェクトを吹き飛ばすしているのでfailure.moveは機能
[このページはMDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_theprototype_chain)にお読みください。あなたは 'Classes' /' Subclass'/'Superclass'のものをすべて必要とすべきではありません... –
私の質問は\tの違いは何ですか?Subclass.prototype.dance = function(x、y){ }; 'と ' Subclass.prototype = {dance:function(){}}; '? – Daniela