this指针

110 阅读1分钟

this指针:

是 JavaScript this 关键字

面向对象语言中 this 表示当前对象的一个引用。

但在 JavaScript 中 this 不是固定不变的,它会随着执行环境的改变而改变。

  • 在方法中,this 表示该方法所属的对象。
  • 如果单独使用,this 表示全局对象。
  • 在函数中,this 表示全局对象。
  • 在函数中,在严格模式下,this 是未定义的(undefined)。
  • 在事件中,this 表示接收事件的元素。
  • 类似 call() 和 apply() 方法可以将 this 引用到任何对象。

以下分三种情况简单的描述一下

1、在函数体外,this指向window

console.log(this);//此时this指向window

2、在函数体内,this指向由函数调用者来决定的(谁调用就指向向谁)

`<button id="btn1">按钮</button>
<button id="btn2">按钮</button>`

`var btn1 = document.getElementById('btn1');
var btn2 = document.getElementById('btn2');`

2-1、嵌套函数this指向直接调用者(this冲突问题)

btn1.onclick = function (){
	setInterval(function (){
	console.log(this);//window (setInterval 是window对象的方法)
	}, 3000);
}

fun内部的this指向的是window

形参_this的实参是指向调用者的this

3、this更多的是用在对象中,this指向的当前对象

var obj = {
				name: '小明',// obj的属性
				age: 18,
				sex: '男',
				fun: function (){//obj的方法
				//console.log(this);
return this.name + ':' + this.age + ":" + this.sex;
					//此处的this指向obj
				}
			};
			//obj.fun();//obj对象中的方法调用
			console.log(obj.fun())