浅谈javascript函数中的this

2014-06-09
浏览
导读:1) 当一个函数被保存为对象的一个属性时,我们称它为一个方法。当一个方法被调用时,this被绑定到该对象。 2) 当一个函数并非一个对象的属性,那么当它被调用时

1) 当一个函数被保存为对象的一个属性时,我们称它为一个方法。当一个方法被调用时,this被绑定到该对象。

2) 当一个函数并非一个对象的属性,那么当它被调用时,this被绑定到全局对象。这一缺陷导致内部函数的this不一定是调用它的函数的this,解决办法是在外部函数定义一个新的变量指向this(例如var that = this; )。

3) 在一个函数前面带上new,将创建一个新对象,this绑定到新对象。

4) apply可以模拟一个对象拥有并执行该函数的场景,第一个参数传递对象给this,null可表示全局对象window,第二个参数传递函数执行时所需的参数序列。

测试代码如下:

var myObject={"a":"init a","b":"init b","":"empty"};     
pt("myObject[\"\"]");//属性名可以是空字符串     
        
myObject.outerFunc=function(myStr){     
    var that=this;//定义that供内部函数访问     
    var innerFunc=function(myStr){     
        //内部函数this没有指向myObject     
        put("in innerFunc \"this\" is " + (typeof this.b));     
        if(typeof that==="undefined"){     
            put("that is undefined");     
        }else{     
            //用that代替this     
            put("use \"that\" reset b");     
            that.b=myStr;     
        }     
    };     
    innerFunc("reset b");     
    this.a=myStr;     
}     
        
        
pt("myObject.a");     
pt("myObject.b");     
put("call outerFunc...");     
myObject.outerFunc("reset a");     
pt("myObject.b");     
pt("myObject.a");     
        
var Quo = function(string){     
    this.status = string;     
};     
Quo.prototype.get_status = function(){     
    return this.status;     
};     
var myQuo = new Quo("confused");     
pt("myQuo.get_status()");     
        
var add = function(a,b){     
    put(this.location);//后面会传window给this     
    return a+b;     
}     
        
var myArray = [3,4];     
var sum = add.apply(null,myArray);//相当于window.add(myArray[0],myArray[1])     
pt("sum");     
        
        
var statusObject = {     
    status: "A-OK"
};     
var status = Quo.prototype.get_status.apply(statusObject);//相当于statusObject.get_status()     
pt("status");

js代码实现轮播图

js实现上传按钮并显示缩略图小轮子

js实现无缝轮播图特效

Node.js API详解之 os模块用法实例分析

详解react组件通讯方式(多种)