2016-11-22 3 views
0

私は後でいくつかのコールバックを追加するように設計されたクラスを持っているとしましょう。各クラスインスタンスで新しいクラスを作成する代わりに、共通の空の関数を使用する方が効率的ですか?

function myclass() { 
    this.onSomething = function() {}; 
    this.onOtherThing = function() {}; 

    this.something = function() { 
     // stuff 
     this.onSomething(); 
    }; 

    this.otherThing = function() { 
     // other stuff 
     this.onOtherThing(); 
    }; 
} 

私はthis.onSomethingthis.onOtherThingは、それらがsomething()otherThing()で呼び出されたときに、エラーがスローされますので、その種類は関数ではないことを示すundefinedまたはnullであることはできません。

空の関数が必要ですが、メモリを使用しているので、これを行うとクラスのメモリ効率が向上しますか?

function myclass() { 
    this.onSomething = empty; 
    this.onOtherThing = empty; 
    ... 
} 

function empty() { 

} 

このように、各クラスインスタンスのプロパティは、毎回新しい関数を作成するのではなく、同じ空の関数をポイントします。私は、空のメソッドを定義することは、多くのメモリを取らないと思うが、それでも...これは技術的に優れているのだろうか?

答えて

1

あなたは新しい機能があなたのクラスのすべてのインスタンスのために作成されているという事実について正しいです。すべてのインスタンス間で共有これを持つためには、クラスのプロトタイプにそれを宣言することができます。

var MyClass = function() { 
    this.something = function() { 
     // stuff 
     this.onSomething(); 
    }; 

    this.otherThing = function() { 
     // other stuff 
     this.onOtherThing(); 
    }; 
} 

MyClass.prototype.onSomething = function() {}; 
MyClass.prototype.onOtherThing = function() {}; 

この方法で、この方法は、すべてのインスタンスで共有されます。

0

なぜ空の関数を返すのではなく、return trueまたはreturn falseにしてみてください。 または最高のあなたが使用することができます。

function myclass() { 
    this.onSomething = false; 
    this.onOtherThing = false; 
    ... 
} 

あなたが試すことができますあなたのコメントのとおり:

function myclass() { 
    this.onSomething = empty(); 
    this.onOtherThing = empty(); 
     ... } 

function empty() { 
    //return something 
    return true; 
} 
+0

'something()'が 'this.onSomething'を呼び出すと、' Uncaught TypeError:falseは関数ではありません。 ' –

+0

大丈夫です。 'function myclass(){ this.onSomething = empty();を試すことができます。 this.onOtherThing = empty(); ... } function empty(){ //何かを返す return true; } ' – candidJ

+0

再び。 'empty()'が 'true'を返すので、' this.onSomething = empty(); 'はthis.onSomething'が' true'を意味します。 'something()'が 'this.onSomething'を呼び出すと、' Uncaught TypeError:this.onSomethingは関数ではありません 'ということになります。実際の関数ではないブール値です。 –

関連する問題