• js 中两个小括号 ()() 用法


    有如下代码:

    (function()
    {
        alert(
    "cftea");
    })();

     其实这段代码的意思就是执行这个匿名函数,弹出提示框,内容为“cftea”。可以把上述代码理解为:

    function foo()
    {
        alert(
    1);
    }
    foo();
    其实相同的功能还有另外两种写法,我们一并列出来如下:
    //1
    function foo(){
        alert(
    "cftea");
    }
    foo();

    //2
    (function(){
        alert(
    "cftea");
    })();

    //3
    (function(){
        alert(
    "cftea");
    }());

    //4
    void function(){
        alert(
    "cftea");
    }()

     

    用途

        说了这么多,这东西到底有什么用呢?它可以立即执行一段代码,并把结果赋给变量;打破我们常规的先写函数,再调用的流程,简化书写。

    转自:http://www.cftea.com/c/2009/06/C8NJ1VM7SV9RWKHD.asp
     

    JavaScript 两个小括号 ()() 对执行上下文的影响

        先看代码:

    function Foo() {
        
    var a = 123;
        
    this.a = 456;
        (
    function() {
            alert(a); 
    // 123
            alert(this.a); // undefined
        })();
    }
    var f = new Foo();

         以上代码,先显示 123,再显示 undefined,说明 alert(this.a); 这句中 this 是指本 function 的,而不是其外部 function 的。如果要使用外部的成员,可使用参数的形式传入:

    function Foo() {
        
    var a = 123;
        
    this.a = 456;
        (
    function(a) {
            alert(a); 
    // 456
        })(this.a);
    }
    var f = new Foo();
    再看看下面的:
    function Foo() {
        
    var a = 123;
        
    this.a = 456;
        (
    function() {
            alert(a); 
    // 123
            alert(this.a); // undefined
            this.b = 789;
        })();

        (
    function() {
            alert(
    this.b); // 789
        })();
    }

    var f = new Foo();

    function() {
        alert(
    this.b); // 789
    })();

         同样是先显示 123,然后显示 undefined,然后显示 789,最后又是一个 789。这说明用两个小括号括起来的都是位于一个执行上下文中的,不论这些代码放在哪里。

         再看看:
    function Foo() {
        (
    function() {
            
    this.b = 789;
        })();
        (
    function() {
            alert(
    this.b); // 789
            var b = 0;
            alert(b); 
    // 0
        })();
    }
    var f = new Foo();
    (
    function() {
        alert(
    this.b); // 789
        alert(b); // 789
    })();
        令人意外的是,最后一个 alert(b),结果仍然是 789。  
        从上,我们可以看出,取值时、没有加 this 时:如果当前 () 中不存在同名的局部变量,则等同于加 this 处理;如果当前 () 中存在同名的局部变量,则按常规处理。

    转自:http://www.cftea.com/c/2009/08/SQM26L9XH6CF1OCY.asp

  • 相关阅读:
    ST的电机开发硬件套件NUCLEO-G431RB和X-NUCLEO-IHM16M1
    计算机软件世界的思维方式
    vue 动态路由配置,路由由后台返回
    element Cascader组件通过最后一级ID查找匹配的父级ID
    git push本地代码成功,远程提交未更新
    面试整理之原理问题
    JS执行环境与作用域理解
    webpack原理类型问题
    __webpack_require__(...) is not a function
    express+cors模拟解决跨域
  • 原文地址:https://www.cnblogs.com/scottckt/p/2160368.html
Copyright © 2020-2023  润新知