コード例:prototype.objectで 'this'コンテキストを正しくバインドする方法はありますか?
function Test() {
this.name = 'test'
}
Test.prototype.normal = function() {
console.log('normal', this.name);
};
Test.prototype.special = {
name: 'special',
start: function() {
console.log("special", this.name);
}
}
test = new Test;
test.normal(); // Response 'normal, test'
test.special.start(); // Response 'special, special'
に私はどのように私はこれを達成することができます「特別な、テスト」
をログに記録するspecial.start
機能が欲しいですか?私はcoffeescriptを使用しているので、コーヒーの例が分かりますが、javascriptの例も同様に動作します!前もって感謝します!
あなたは実際にここで何を達成しようとしていますか?そして、関数の通常の 'this'は、関数Testにスコープされていません。 'special.start'はプロトタイプにスコープされていません。 'this'値はすべての呼び出しでJavaScriptランタイムによって動的に設定されます。 –
ああ、情報ありがとうございました – Dex
'Test.prototype.special.start = Test.prototype.special.start.bind(this);' - ただ** no **。プロトタイプを再バインドしています。これは、すべての単一インスタンスに影響します。 'test2 = new Test'と' test3 = new Test'を追加すると、本当に混乱する結果になります。 – deceze