js 一个例子弄清楚this的所有指代情况

this的四个原则:

  1. 函数预编译过程,this指向window,函数1内的函数2预编译过程,this指向函数1;
  2. 全局作用域时,this指向window
  3. call/apply/bind可以改变this指向
  4. obj.func(),func()内的this指向obj,谁调用指向谁

实例

var obj = {
	name: 'doudou',
	say: function() {
		test();
	}
}
function test() {
	console.log(this.name)
}
var name = 'feifei';
console.log(this.name); //feifei
test(); //feifei
test.call(obj); //doudou
obj.say(); //feifei

分析如下:

  1. console.log(this.name),此时为全局作用域,this指向window,输出feifei
  2. 执行test(),预编译test时,this指向window,输出feifei
  3. 指向test.call(obj),改变this指向obj,输出obj.name,doudou
  4. 执行obj.say(),此时say()内this指向obj,但执行test,test预编译时,this指向window,输出feifei,如果say改为function() {test.call(obj)}, 改变this指向obj,输出obj.name doudou
发布了53 篇原创文章 · 获赞 12 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/bingqise5193/article/details/100078399
今日推荐