我对JavaScript函数感到困惑吗?

问题描述:

JavaScript函数是否附加到他们定义的任何特定对象或全局对象本身,我问这个问题,因为你几乎可以在任何对象上使用函数,天气函数是否是该对象的一部分,我的意思是你可以指定函数引用你想要的任何对象,这意味着函数本身存储在其他地方,然后我们将它们分配给任何其他对象方法。我对JavaScript函数感到困惑吗?

请改正我我是JavaScript新手,但我对JavaScript有一定了解。

我知道使用这个关键字是用来引用当前的上下文代码。

+0

我知道这个功能取决于它的调用方式 – user2019110 2013-02-16 06:06:38

+4

当发布到堆栈溢出时,请发布更好的标题。 – 2013-02-16 06:06:47

+1

我们无法给出答案,因为我们看不到任何您参考的代码。请提供代码。 – 2013-02-16 06:07:18

函数没有附加到任何东西,但执行时,它们在this绑定到某个对象(除了ES5严格模式,其中this有时可能未定义)的上下文中这样做。

哪个对象this指是的函数是如何调用的产品,如果它是为一个对象中的一员,或如callapply是否一个功能被使用。

var obj = { 
    x: 20, 
    fn: function() { 
    console.log(this.x); 
    } 
}; 
obj.fn(); // prints 20 as `this` will now point to the object `obj` 

var x = 10; 
var fn = obj.fn; 
fn(); // prints 10 as `this` will now point to the global context, since we're invoking the function directly 

var newObj = { 
    x: 30 
}; 
fn.call(newObj); // prints 30 as `this` points to newObj 
fn.apply(newObj); // same as the above, but takes an the functions arguments as an array instead of individual arguments 
+0

非常感谢你,kinsey你救了我的灵魂。 – user2019110 2013-02-16 07:23:38