|
情况一:纯粹的函数调用
这是函数的最通常用法,属于全局性调用,因此this就代表全局对象。 var x = 1;
function test() {
console.log(this.x); // 1
}
test();
情况二:作为对象方法的调用 函数还可以作为某个对象的方法调用,这时this就指这个上级对象。 function test() {
console.log(this.x);
}
var obj = {};
obj.x = 1;
obj.m = test;
obj.m(); // 1
情况三 作为构造函数调用 所谓构造函数,就是通过这个函数,可以生成一个新对象。这时,this就指这个新对象 function test() {
this.x = 1;
}
var obj = new test();
obj.x // 1
情况四 call/apply 调用 apply()是函数的一个方法,作用是改变函数的调用对象。它的第一个参数就表示改变后的调用这个函数的对象。因此,这时this指的就是这第一个参数。 var x = 0;
function test() {
console.log(this.x);
}
var obj = {};
obj.x = 1;
obj.m = test;
obj.m.apply() // 0
obj.m.apply(obj); //1
情况四 五:定时器函数调用 这里autoplay的this是全局 var tim=setInterval(autoPlay,2000); |
|
最新喜欢: |