为什么要写“.call(this)”在一个javascript匿名函数的末尾? [英] Why write ".call(this)" at the end of an javascript anonymous function?

查看:142
本文介绍了为什么要写“.call(this)”在一个javascript匿名函数的末尾?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过这样写的JavaScript(它是在演示中,我手头没有实际代码,但暗示这是正常的):

I have seen JavaScript written like this (it was at a demonstration, and I don’t have the actual code at hand, but it was implied this was normal):

(function() {    

    var a = 1;

    this.sayA = function() {
        alert(a);
    }

}).call(this);

sayA();

我想它是一个匿名函数,所以变量 a 不是全球可用。

I suppose it is written an an anonymous function so that the variable a is not globally available.

.call(this)的重点是什么?是?由于此函数未嵌套,只是窗口。它与仅在最后写()有什么不同?

What could the point of the .call(this) be? Since this function was not nested, this was just the window. How does it differ from just writing () at the end?

推荐答案

试试这个:

function Foo() {

  (function () {
    console.log(this);
    // > Foo
  }).call(this);

  (function () {
    console.log(this);
    // > undefined in strict mode, or Window in non strict mode
  })();
}

var bar = new Foo;

因此,如果出于任何原因你使用它,这是一种使 IIFE 表现得好像它是 Foo的成员函数,特别是在创建用户定义对象类型的实例时。

So, if for whatever reason you use this, it's a way to make the IIFE act as if it were a member function of Foo, specifically when creating instances of a user-defined object type.

这篇关于为什么要写“.call(this)”在一个javascript匿名函数的末尾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆