JavaScript: Class.method と Class.prototype.method 質問する

JavaScript: Class.method と Class.prototype.method 質問する

次の 2 つの宣言の違いは何ですか?

Class.method = function () { /* code */ }
Class.prototype.method = function () { /* code using this.values */ }

最初の文を静的メソッドの宣言、2 番目の文をインスタンス メソッドの宣言と考えてよいですか?

ベストアンサー1

はい、最初の関数はそのオブジェクトのインスタンスとは何の関係もありませんコンストラクタ関数、これを「静的メソッド」のように考えることができます。

JavaScriptの関数はファーストクラスオブジェクトは、他のオブジェクトと同じように扱うことができます。この場合は、関数オブジェクトにプロパティを追加するだけです。

2番目の関数は、コンストラクタ関数のプロトタイプを拡張しているので、作成されたすべてのオブジェクトインスタンスで使用できます。newキーワードとその関数内のコンテキスト(thisキーワードは、呼び出した実際のオブジェクト インスタンスを参照します。

次の例を考えてみましょう。

// constructor function
function MyClass () {
  var privateVariable; // private member only available within the constructor fn

  this.privilegedMethod = function () { // it can access private members
    //..
  };
}

// A 'static method', it's just like a normal function 
// it has no relation with any 'MyClass' object instance
MyClass.staticMethod = function () {};

MyClass.prototype.publicMethod = function () {
  // the 'this' keyword refers to the object instance
  // you can access only 'privileged' and 'public' members
};

var myObj = new MyClass(); // new object instance

myObj.publicMethod();
MyClass.staticMethod();

おすすめ記事