zoukankan      html  css  js  c++  java
  • call(this)引起的对闭包的重新理解

    call(this)引起的对闭包的重新理解.md

    变量的作用域

    全局变量
    局部变量

    Javascript语言的特殊之处,就在于函数内部可以直接读取全局变量。

    函数外部无法读取函数内的局部变量。

    函数内部声明变量的时候,一定要使用var命令。如果不用的话,你实际上声明了一个全局变量!

    (function(){……}).call(this);
    

    (function(){……})();//是闭包的经典用法,内定义的变量,在外肯定是无法访问的

    (function(a){c = 1; alert(this.c);})//什么都没有
    (function(a){this.c = 1; alert(this.c);})() //alert(“1”);

    (function(){c = 1; alert(this.c);}).call(this);//alert(“1”);

    (function(a){c = a; alert(this.c);}).call(this,”5”)//alert(“5”);

    试了这就没什么用:(哭)

    看看下面的例子:

    var a = {
        b : function(){
            this.c = 1;//此时的this指向b
        }
    }
    

    > a.c //undifined
    > a.b(); //此时调用b方法,this指向了a
    > a.c //1
    > this.c; //undifined 此时this为window
    > a.b.call(this) //此时将this指向了window
    > this.c //1
    > a.c //1
    > c //1

    (function(){var a = {
    b : function(){
    this.c = 1;//此时的this指向b
    }
    }
    this.d = 3; alert(this.c);})()

    (function(){var a = {
    b : function(){
    this.c = 1;//此时的this指向b
    }
    }
    this.d = 3; alert(this.c);}).call(this)

    http://i.h-won.com/post/2013-08-29/40052244462

    https://github.com/klamtlne/Validator

    W3School上面解释:call()方法是与经典的对象冒充方法最相似的方法。

    function sayColor(sPrefix,sSuffix) {
        alert(sPrefix + this.color + sSuffix);
    };
    

    var obj = new Object();
    obj.color = “blue”;

    sayColor.call(obj, “The color is “, “a very nice color indeed.”);

    //”The color is blue, a very nice color indeed.

    实例2:

    function ClassA(sColor) {
        this.color = sColor;
        this.sayColor = function () {
            alert(this.color);
        };
    }
    

    function ClassB(sColor, sName) {
    //this.newMethod = ClassA;
    //this.newMethod(color);
    //delete this.newMethod;
    ClassA.call(this, sColor);

    this.name = sName;
    this.sayName = function () {
        alert(this.name);
    };
    

    }

    var objA = new ClassA(“blue”);
    var objB = new ClassB(“red”, “John”);
    objA.sayColor();
    objB.sayColor();
    objB.sayName();

    -----------------------------------------------------------------------
    Simple is Beautiful,Less is More.
    --FuGardenia
  • 相关阅读:
    树莓派安装parrot linux记录
    Arch linux(UEFI+GPT)安装及后续优化教程
    VS部分安全函数用法
    C语言博客作业06--结构体&文件
    C语言博客作业05--指针
    C语言博客作业04--数组
    C语言博客作业03--函数
    C语言博客作业02--循环结构
    DS博客作业08--课程总结
    DS博客作业07--查找
  • 原文地址:https://www.cnblogs.com/yunqianduan/p/4012831.html
Copyright © 2011-2022 走看看