js的this指针

this是js的一个关键字,指向当前函数的调用对象。

1、函数调用

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

this指向全局对象window

另一种形式可以证明this指向window

var v = 1;
function test() {
this.v = 2;
}
test(); //2

只要是function test(){} or test()这种形式,在函数内部,this都指向window。

eg:

test.method = function() {

function test() {

//this指向window

}

}

var test = obj.method;

test(); //函数内,this指向window而非obj。

2、作为对象方法调用

function test() {
alert(this.v);
}
var o = {};
o.v = 1;
o.m = test;
o.m(); //1

函数作为某个对象的方法调用的时候,this指向的是当前函数的调用对象。

经典例子(实现点击start按钮,启动计时;点击stop按钮,暂停当前计时):

涉及知识点(闭包、setInterval&setTimeout区别、this指针)。

(function() {
	function counter(num) {
		this.num = num;
	}; 
	counter.prototype = {
	   show: function() {
	       document.getElementById('text').innerHTML = this.num++;
	   },
	   start: function() {
	       //此时this指向函数调用对象c
	       this.stop();
	       var me = this;  //保存当前this指向的对象c
	       //setInterval为window对象的方法,它的第一个参数的函数在全局作用域执行,因此this指向window,要想调用show(),必须先缓存c,
	       console.log(this === c);    //true,this指向c
	       this._timer  = setInterval(function() {
	           console.log(this === c);    //false,this指向window
	           me.show();
	       }, 1000);
	   },
	   stop: function() {
	       clearInterval(this._timer);
	   }
	};
    var c = new counter();
    c.start();
})();

3、作为构造函数

function test() {
this.v = 1;
}
var o = new test();
alert(o.v); //1

也就是说作为构造函数的时候,this指向的是新对象。

4、apply调用

apply( )在犀牛书里面的解释是,调用一个对象的方法,以另外一个对象替换当前对象,也就是改变当前函数的作用域。

当使用Function.prototype的call( obj, 1, 2, 3)  or apply(obj, [1, 2, 3])方法时,函数的this指向函数的第一个参数,也就是obj。

var v = 1;
function test() {
alert(this.v);
}
var o = {};
o.v = 2;
o.m  = test;
o.m.apply(); //这里要注意,当apply( )参数为空的时候,默认调用window。所以这里alert出来的是1

若改为o.m.apply(o); //2


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值