我对JavaScript函数感到困惑?

时间:2013-02-16 06:05:10

标签: javascript function

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

请更正我,我是JavaScript的新手,但我在某种程度上了解JavaScript。

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

1 个答案:

答案 0 :(得分:2)

函数没有附加到任何东西,但是在执行时它们是在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
相关问题