内部method()
メソッドを表す関数オブジェクトではなく、メソッドが呼び出されるオブジェクトのプロパティを設定しています。
これは、メソッドの内部の違いを示しています
this.method = function() {
this.parameter = 'abc'; // Set parameter on the object on which method() is called
this.method.parameter = 'xyz'; // Set parameter on the object representing the method itself
};
これは、あなたが機能上の特性を必要とするかどうかを決める必要があるメソッドの後にプロパティにアクセスするに差が
p.method();
console.log(p.parameter); // Display property of the object p, equals 'abc'
console.log(p.method.parameter); // Display property of the function object representing method(), equals 'xyz'
と呼ばれる示しオブジェクトまたはp
オブジェクトにあります。ファンクションオブジェクトは、Main()
コンストラクタによって作成されたいくつかのオブジェクトによって共有されることがあります。したがって、C++やJavaのような言語の静的メンバーにいくらか類似した振る舞いをします。
あなたがオブジェクトに定義されたプロパティを使用する場合は、あなたのコードは次のようになります。
function Main() {
this.method = function() {
this.parameter = 'something_relevant'; // Set property on object on which method() is called.
};
}
var p = new Main();
p.method();
console.log(p.parameter); // Read property from object p.
あなたがmethod()
を表す関数オブジェクトで定義されたプロパティを使用する場合は、あなたのコードは似たものになりますこれに:
あなたが内部 `console.log`を配置する場合、` method`呼び出しは、非同期であるためである
function Main() {
this.method = function() {
this.method.parameter = 'something_relevant'; // Set property on function object representing method().
};
}
var p = new Main();
p.method();
console.log(p.method.parameter); // Read property from the function object.
'this.method'を割り当てた後、それが動作します。 – Cyclonecode
@Krister Andersson:ここでは、非同期のものはありません。 – pimvdb