zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    欧拉定理 (证明+在求逆元上的应用)
    【转】弱校的ACM奋斗史
    SDUT 2412 (单调队列 + dp)
    做SRM感想。。。
    平面图中最小割向最短路的转化
    HDU 4533
    黑书上的DP 30题
    POJ【数论/组合/博弈论】题目列表
    HDU 4534 郑厂长系列故事——新闻净化
    SRM 571
  • 原文地址:https://www.cnblogs.com/scottckt/p/2160368.html
Copyright © 2011-2022 走看看