您好,欢迎访问一九零五行业门户网

javascript运行机制之this详细介绍_基础知识

this是面向对象语言中一个重要的关键字,理解并掌握该关键字的使用对于我们代码的健壮性及优美性至关重要。而javascript的this又有区别于java、c#等纯面向对象的语言,这使得this更加扑朔迷离,让人迷惑。
this使用到的情况:
1. 纯函数
2. 对象方法调用
3. 使用new调用构造函数
4. 内部函数
5. 使用call / apply
6.事件绑定
1. 纯函数
复制代码 代码如下:
var name = 'this is window';  //定义window的name属性 
function getname(){ 
       console.log(this);    //控制台输出: window  //this指向的是全局对象--window对象 
       console.log(this.name);  //控制台输出: this is window  / 
}
getname();
运行结果分析:纯函数中的this均指向了全局对象,即window。
2. 对象方法调用
复制代码 代码如下:
var name = 'this is window';  //定义window的name属性,看this.name是否会调用到 
var testobj = { 
    name:'this is testobj', 
    getname:function(){ 
        console.log(this);  //控制台输出:testobj   //this指向的是testobj对象 
        console.log(this.name);  //控制台输出: this is testobj 
    } 
}
testobj.getname();
运行结果分析:被调用方法中this均指向了调用该方法的对象。
3.  使用new调用构造函数
复制代码 代码如下:
function getobj(){ 
    console.log(this);    //控制台输出: getobj{}  //this指向的新创建的getobj对象 
}
new getobj();
运行结果分析:new 构造函数中的this指向新生成的对象。
4. 内部函数
复制代码 代码如下:
var name = this is window;  //定义window的name属性,看this.name是否会调用到 
var testobj = { 
    name : this is testobj, 
    getname:function(){ 
        //var self = this;   //临时保存this对象 
        var handle = function(){ 
            console.log(this);   //控制台输出: window  //this指向的是全局对象--window对象 
            console.log(this.name);  //控制台输出: this is window   
            //console.log(self);  //这样可以获取到的this即指向testobj对象 
        } 
        handle(); 
    } 
}
testobj.getname();
运行结果分析:内部函数中的this仍然指向的是全局对象,即window。这里普遍被认为是javascript语言的设计错误,因为没有人想让内部函数中的this指向全局对象。一般的处理方式是将this作为变量保存下来,一般约定为that或者self,如上述代码所示。
5. 使用call / apply
复制代码 代码如下:
var name = 'this is window';  //定义window的name属性,看this.name是否会调用到 
var testobj1 = { 
    name : 'this is testobj1', 
    getname:function(){ 
        console.log(this);   //控制台输出: testobj2  //this指向的是testobj2对象 
        console.log(this.name);  //控制台输出: this is testobj2   
    } 
}
var testobj2 = { 
    name: 'this is testobj2' 
}
testobj1.getname.apply(testobj2); 
testobj1.getname.call(testobj2);
note:apply和call类似,只是两者的第2个参数不同:
[1] call( thisarg [,arg1,arg2,… ] );  // 第2个参数使用参数列表:arg1,arg2,... 
[2] apply(thisarg [,argarray] );     //第2个参数使用 参数数组:argarray
运行结果分析:使用call / apply  的函数里面的this指向绑定的对象。
6. 事件绑定
事件方法中的this应该是最容易让人产生疑惑的地方,大部分的出错都源于此。
复制代码 代码如下:
//页面element上进行绑定
点击
复制代码 代码如下:
//js中绑定方式(1)
点击
复制代码 代码如下:
//js中绑定方式(2)
点击
复制代码 代码如下:
//js中绑定方式(3)
点击
运行结果分析:以上2种常用事件绑定方法,在页面element上的进行事件绑定(onclick=btclick();),this指向的是全局对象;而在js中进行绑定,除了attachevent绑定的事件方法外,this指向的是绑定事件的elment元素。
其它类似信息

推荐信息