这个关键字的JavaScript如何运作?

时间:2011-07-13 01:22:28

标签: javascript object this

我一直在做一些JavaScript开发,我遇到了这个问题。请考虑以下代码

var obj = {};
obj.bind = function () {
console.info(this);
};

obj.bind();

我在FireBug JavaScript控制台上运行代码。预期的结果是this显示对控制台中对象的引用。

它实际显示undefined

但是,当我对我的代码进行此更改时

var obj = {};
obj.bind = function () {
this.x = 'x';
console.info(this);
};

obj.bind();

现在,控制台显示this的预期值,这是对obj对象的引用。

为什么会这样?

2 个答案:

答案 0 :(得分:3)

undefined是函数的返回值,因为你没有明确地返回一个值,所以你会得到它。

在Chrome和Firebug中,它在返回值undefined之前正确显示控制台中的对象。

所以,如果你这样做:

var obj = {};
    obj.bind = function () {
    console.info(this);
    return "foo";
};

obj.bind();

......你应该看到类似的东西:

Object {   }
"foo"

如果Firebug为空时没有显示对象,则可能需要检查以确保您使用的是最新版本。

答案 1 :(得分:-1)

在你的例子中,“this”应该是obj,正如一些评论者指出的那样。以下是解释原因的详细信息 -

在Javascript中,“this”的值会根据您调用函数的方式而改变:

  1. 当函数作为属性存储在对象上,并且通过调用obj.foo()调用该函数时,“this”将是obj。
  2. EX:

    var obj = {
      x: 1,
      increment: function() {
        this.x = this.x + 1;
    };
    
    obj.increment(); // Makes "this" be obj
    
    1. 当您使用不引用任何拥有对象的语法调用函数时,“this”将是全局环境。
    2. EX:

      function someFunc(a, b) {
           return a + b; // If you were to refer to "this" here, it would be the global env.
      }
      
      someFunc(5, 6);
      
      1. 当你通过使用new运算符调用一个函数就好像它是一个构造函数时,将为你实例化一个新对象,并且“this”将指向该新对象。
      2. EX:

        function SomeConstructor() {
           this.x = 42; // under the hood, a new object was instantiated for you, and "this" was set to it.
        }
        
        var result = new SomeConstructor(); // note the "new" keyword
        

        //结果将是{x:42}

        1. 当你使用call()或apply()时,你可以控制“this”是什么。
        2. (这里没有例子,因为它离你的问题相当远。查看doc()或者调用()的文档作为例子。)