timeOut を使用するときに、この参照を保持するにはどうすればよいですか?
var o = {
f:function(){
console.log(this)
setTimeout(this.f,100);
}
}
o.f();
このコードを実行すると、this
参照が間違っています...何が欠けていますか?
timeOut を使用するときに、この参照を保持するにはどうすればよいですか?
var o = {
f:function(){
console.log(this)
setTimeout(this.f,100);
}
}
o.f();
このコードを実行すると、this
参照が間違っています...何が欠けていますか?
パラメータを 3 番目のパラメータとして setTimeout に渡すことができます。そうすれば、参照を渡すことができます。
ただし、「オブジェクト指向」のものを new で作成しようとしている場合は、代わりに次のように関数を使用する必要があります。
function obj() {
this.publicFunction = function() {
console.log("I'm public!");
};
var privateFunction = function() {
console.log("Only accessible from inside this instance!");
}
}
var objInstance = new obj();
objInstance.publicFunction(); // Logs w/o problem
objInstance.privateFuntion() // Undefined!
EDIT(再び):
しかし、何らかの理由でオブジェクトを使用したい場合はthis
、実際にはオブジェクト自体を参照します。ただし、オブジェクトは変数として定義されているため (この場合はグローバルでもあります)、代わりに名前を直接参照できますthis
。ここ:
var o = {
f: function() {
console.log(this); // Will log the object 'o'
console.log(o); // Same as above
}
};
setTimeout(o.f, 100);
これは、呼び出し方法によって異なります。詳細については、他のスタックオーバーフローの回答を参照してください。
f() は o のメンバーですが、of は timeout に渡され、関数呼び出しで呼び出される関数です。これにより、望ましい結果が得られます。
var o = {
f:function(){
console.log(o)
setTimeout(o.f,100);
}
}
o.f();
関数呼び出しで呼び出されるメンバー関数の別の例を次に示します。
var anObject = {
test: function(isThis, message) {
if(this === isThis)
console.log("this is " + message);
else
console.log("this is NOT " + message);
}//I am a method
};
//method invocation
anObject.test(anObject, "anObject"); //this is anObject
var aFunction = anObject.test;
//functional invocation
aFunction(anObject, "anObject with aFunction"); //this is NOT anObject with aFunction
aFunction(this, "global with aFunction");//this is global with aFunction
お役に立てれば。