"这个"在javascript函数中?

nev*_*ame 4 javascript

我理解"this"是调用者对象的引用.

我习惯在代码中看到"this",如:

var Person = function() {
   this.name = "foo";
}
Run Code Online (Sandbox Code Playgroud)

但后来我看到了这些代码:

例1:

function helloWorld1() {
   this({ body: "Hello world!" })();
}
Run Code Online (Sandbox Code Playgroud)

例2:

我也看过这段代码:

function helloWorld2() {
  this
    ({ body: "Hello, " })
    ({ body: "world!" })
    ();
}
Run Code Online (Sandbox Code Playgroud)
  • "这个"在这里意味着什么?
  • 上面的例子中发生了什么?

CMS*_*CMS 8

实际上this可以引用不同的东西,隐含地,它是根据你如何调用一个函数来设置的,例如:

obj.func();
Run Code Online (Sandbox Code Playgroud)

this里面的值func将参考obj.

new Func();
Run Code Online (Sandbox Code Playgroud)

该this值将引用从中继承的新创建的对象Func.prototype.

func();
Run Code Online (Sandbox Code Playgroud)

该this值将引用Global对象.

并且可以使用或方法显式设置值,例如:callapply

function foo () {
  alert(this);
}

foo.call("hello world");
Run Code Online (Sandbox Code Playgroud)

helloWorld1您发布的示例仅在this值引用函数时才起作用,该函数返回另一个函数,因为如果您分析该行:

this({ body: "Hello world!" })();
Run Code Online (Sandbox Code Playgroud)

您可以注意到this需要是一个函数,因为您正在调用它,将对象传递给它.而且我们知道返回值也需要是一个函数,因为最后的括号是另一个函数调用.

例如:

var fn = function(o){
  return function () {
    alert(o.body);
   }
};
helloWorld1.call(fn);  // or the equivalent

fn.method = helloWorld1;
fn.method();
Run Code Online (Sandbox Code Playgroud)

编辑:要使helloWorld2您发布工作的示例,该this值必须是一个函数,其模式允许我们链接多个函数调用,每次返回相同的函数,直到函数被调用而不带参数,例如:

var fn = (function(){
  var msg = '';
  return function inner (o) {
    if (o) { // called with an argument?
      msg += o.body;
    } else { // no, show the message
      alert(msg);
    }
    return inner; // return a reference to itself
  };
})();

function helloWorld2() {
  this
  ({ body: "Hello, " })
  ({ body: "my " })
  ({ body: "world!" })
  ();
}
helloWorld2.call(fn); // "Hello my world!"
Run Code Online (Sandbox Code Playgroud)