2016-04-22 98 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'); } 

在这里,你没有提到的var/let/..定义方法,因此slurp将获得分配给window

因此,此代码,

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

等于

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

而且window.self == window。因此你得到true作为结果。

2

this的值取决于如何调用它所显示的函数。

在第一个示例中,您将其称为任何函数之外,在第二个示例中,您将其称为ready事件处理函数。

您可以使用window而不是this(在浏览器中)明确检查它是否是全局的。

+0

是的,但在第二个示例中,我并没有在调用ready事件处理函数时调用的函数内部定义函数slurp。这是我不明白的地方。为什么这个功能目前无法访问。 – Naremy

+1

@Naremy - 在第二个例子中,'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 
}) 
相关问题