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();

转载于:https://www.cnblogs.com/yunqianduan/p/4012831.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值