私はこのコードを持っています
function test(){};
test.prototype.testMethod = function(){return 1;}
var t = new test();
t.testMethod();
ここで、メソッドtestMethodをオーバーライドして、オーバーライドで基本メソッドを呼び出すことができるようにする必要があります。プロトタイプを使用してそれを行うにはどうすればよいですか?
私はこのコードを持っています
function test(){};
test.prototype.testMethod = function(){return 1;}
var t = new test();
t.testMethod();
ここで、メソッドtestMethodをオーバーライドして、オーバーライドで基本メソッドを呼び出すことができるようにする必要があります。プロトタイプを使用してそれを行うにはどうすればよいですか?
個々のインスタンスの基本メソッドを上書きする必要がある場合でも、プロトタイプで定義されたメソッドを参照できます。
function test(){};
test.prototype.testMethod = function() {console.log('testMethod in prototype');}
var t = new test();
t.testMethod = function () {
console.log(this);
console.log('testMethod override');
test.prototype.testMethod();
};
t.testMethod();
試してみてください: http://jsfiddle.net/aeBWS/
プロトタイプ メソッド自体を置き換えたい場合は、いくつかのルートがあります。最も単純な方法は、関数に別の名前を付けることです。それが不可能な場合は、古いメソッドを新しい名前 ( など_testMethod
) のメソッドにコピーして、その方法で呼び出すことができます。
function test(){};
test.prototype.testMethod = function() {console.log('testMethod in prototype');}
test.prototype._oldTestMethod = test.prototype.testMethod;
test.prototype.testMethod = function() {
console.log('testMethod override');
test.prototype._oldTestMethod ();
};
var t = new test();
t.testMethod();
試してみてください: http://jsfiddle.net/x4txH/
次のように、テスト プロトタイプで古いメソッドの参照を使用できます。
function test(){};
test.prototype.testMethod = function(){
return 1;
}
function test2(){};
test2.prototype = new test();
test2.prototype.testMethod = function(){
return test.prototype.testMethod()
};