js的this关键字

this是一个引用。下面有5种this的变化情况:

1.在函数运行时,每个函数都有一个调用它的上下文,而这个this就是指向这个上下文对象。

example:

var test = function(){
	console.log(this);
}
test();//输出window对象
var test = function(){
	var attr1 = 'hello';
	console.log(this);
	console.log(this.attr1);
}
test();//输出window对象和undefined

//Temp构造函数
var Temp = function (attr1,func){
	this.attr1 = attr1;
	this.test = func;
}
var temp = new Temp("world",test);
temp.test();//输出Temp对象和world


2.在构造函数里this指向该函数创建的实例对象的引用,对象Object里this指向该对象引用,我们就可以轻易在该这些对象里调用自己的方法和属性。

example:

//这是test构造函数
var Test = function (attr1, attr2){
	this.attr1 = attr1;
	this.attr2 = attr2;
	this.func = function(){
		console.log(this);//Test创建的对象实例
		console.log(this.attr1);//attr1的值
		console.log(Test.attr1);//undefined
	}
};
//这是object对象
var object = {
	attr1 : 'hello ',
	attr2 : 'world',
	func : function (){
		console.log(this);//object对象
		console.log(this.attr1);//hello
		console.log(object.attr1);//hello
	}
}
var temp = new Test('hello', 'world');
temp.func();//输出Test对象  ,hello, undefined
object.func();//输出object对象, hello, hello


 3.在嵌套函数里的this在ES5规范里指定了一个值,就是window对象。即使这个函数时嵌套在构造函数或对象里,这个this也不会再指向该对象,而是指向了window对象。 

example:

var Test = function (attr1, attr2){
	this.attr1 = attr1;
	this.attr2 = attr2;
	this.func = function(){
		console.log(this);//Test创建的对象实例
		var inner = (function(){
			console.log(this);//window对象

		})();
	}
};
//这是object对象
var object = {
	attr1 : 'hello ',
	attr2 : 'world',
	func : function (){
		console.log(this);//object对象
		var inner = (function(){
			console.log(this);//window对象

		})();
	}
}
var temp = new Test('hello', 'world');
temp.func();//输出Test对象实例  ,hello, undefined
object.func();//输出object对象, hello, hello


4.事件函数,this指向触发的元素。

example:

<!doctype html>
<html>
<head>
	<title>Test</title>
	<script>
		window.onload = funciton(){
			document.getElementById('test').οnclick=function(){
				console.log(this);//输出触发的button对象
			};
		}
	</script>
</head>
<body>
	<button id="test'>click me!</button>
</body>
</html>


 

5.call和apply方法可以改变函数的this。在调用call和apply方法时,传入要this指向的对象。

example:

var test = function(){
	console.log(this);
	console.log(this.attr1);
}
var object = {
	attr1 : 'hello',
	attr2 : 'world'
}
test();//window对象,undefined, [from window]
test.call(object,null);//object对象,hello ,["this ", "is ", "call"] 
test.apply(object,null);//object对象,hello,["this ", "is ", "apply"] 


call和apply的区别是:call只能一个一个参数传入,而apply传入的是数组。



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值