this的常见用法

1. 做为普通的函数调用,this的值为全局对象或者undefined(严格模式下)app

function test() {
this.x = 1;
alert(x);
}
test();

2. 做为方法调用时,this的值指向调用它的对象。函数

function test() {
alert(this.x);
}

var o = {};
o.x = 1;
o.m = test;
o.m(); //1

3. 构造函数中,表示这个新建立的对象this

4.call()和apply()中,this指向的是apply()的第一个参数,没有传递参数时,表示全局对象。对象

var x = 0;function test() {    alert(this.x);}var o = {};o.x = 1;o.m = test;o.m.apply(); //0o.m.apply(o);//15.事件处理程序中e.onclick=function(){}在事件处理程序内,this关键字指的是事件目标
相关文章
相关标签/搜索