2016-04-22 24 views
-2

この関数が定義されている場合にのみ、関数を呼び出す必要があります。私は、ノードまたはブラウザのコンソールで次のコードを試してみると、その作業です。

slurp = function() { console.log('slurp'); } 
slurp_callable = ('slurp' in this && typeof(this['slurp']) == 'function'); 
console.log('slurp is callable (this)?', slurp_callable); 
if (slurp_callable) { this['slurp'](); } 

しかし、私は(jqueryのを使用して)準備ができて、ドキュメントを待つ場合:

$(document).ready(function() { 
    console.log("ready!"); 
    slurp = function() { console.log('slurp'); } 
    console.log('slurp is callable (this)?', ('slurp' in this && typeof(this['slurp']) == 'function')); //False 
    console.log('slurp is callable (self)?', ('slurp' in self && typeof(self['slurp']) == 'function')); //true 
}); 

それは自分のために、このための偽と真の私を返します。

私は自己が私の以前のこの値であることを理解していますが、これはいつ変更されたのですか?

自己を使用せずに関数をチェックして$(document).readyにする方法はありますか?

答えて

1

基本的selfはを指しますwindow.self(オーバーライドしない場合)ここで

slurp = function() { console.log('slurp'); } 

あなたはそれゆえslurpwindowに割り当てられてしまいます、var/let/..定義する方法を言及していません。

ので、このコードは

('slurp' in self && typeof(self['slurp']) == 'function') 

('slurp' in window.self && typeof(window.self['slurp']) == 'function'). 
また

window.self == windowに等しく、です。あなたは結果としてtrueを得ています。

2

thisの値は、その機能がどのように表示されるかによって異なります。

最初の例では、関数の外でそれを呼び出しています(2番目の例では、readyイベントハンドラと呼ばれる関数で呼び出しています)。

ブラウザでthisの代わりにwindowを使用してグローバルであるかどうかを明示的に確認できます。関数の内部

+0

はい、2番目の例では、準備完了イベントハンドラが呼び出されたときに呼び出される関数の内部でも関数slurpを定義していません。それは私が理解していないものです。現在、この機能にアクセスできない理由は何ですか? – Naremy

+1

@Naremy - 2番目の例では、 'slurp'はグローバルで(' window.slurp'と同じですが) 'this'は' window'と同じではないので 'this.slurp'は' undefined'です。 – Quentin

1

$(document).ready(function() { 
    console.log(this); // here this is the document 
}) 

いますが、次のように書いた場合:

console.log(this); // this is window 

$(document).ready(function() { 
    console.log(this); // here this is the document 
}) 

をより明確にするため次の試みることができる:

console.log(this); // this is window 
a = 10; 
console.log(this.a); // 10 

$(document).ready(function() { 
    console.log(this); // here this is the document 
    console.log(this.a); // undefined because a is not defined on the document 

    // but you could access the one defined on the `window` 
    console.log(window.a); // 10 

    b = 10; 
    console.log(this.b); // still undefined because `b` is not set on the document but is local to this function. 

    this.c = 10; 
    console.log(this.c); // 10 
}) 
関連する問題