灏天阁

this 指向问题

· Yin灏

函数内 this 的指向

调用方式 this指向
普通函数调用 window
构造函数调用 实例对象、原型对象里面的方法也指向实例对象
对象方法调用 该方法所属对象
事件绑定方法 绑定事件对象
定时器函数 window
立即执行函数 window

改变函数内部 this 指向

  • bind()
  • call()
  • apply()

call()

// call 第一个可以调用函数,第二个可以改变函数内的 this 指向
var o = {
	name: 'andy'
}

function fn() {
	console.log(this)
}

fn.call(o); // o
// call 的主要作用可以实现继承
function Father(uname, age, sex) {
	this.uname = uname;
	this.age = age;
	this.sex = sex;
}

function Son(uname, age, sex) {
	Father.call(this, uname, age, sex);
}

var son = new Son('刘德华', 18, '男');
console.log(son); // { uname: "刘德华", age: 18, sex: "男" }

apply()

var o = {
	name: 'andy'
}

function fn() {
	console.log(this)
}

fn.apply(o); // o
Math.max.apply(null, [1,2,3,5]); // 这里写 null 不是很合适
// 可以指向函数的调用者 Math
Math.max.apply(Math, [1,2,3,5]);

bind() 方法

不会立即调用函数,但是能改变函数内部 this 指向。

fun.bind(thisArg, arg1, arg2, ...)
/*
  返回由指定的 this 值和初始化参数改造的原函数拷贝
*/
var o = {
	name: 'hao'
}

function fn(a, b) {
	console.log(this, a + b)
}

var f = fn.bind(o, 1, 2); // 完成绑定操作,并没有执行
f(); // { name: "hao" }
  • 实例:点击按钮即禁用,3秒后开启
// bind 不需要立即调用
btn.onclick = function() {
	this.disabled = true;
	setTimeout(function() {
		console.log(this); // window
        this.disabled = false;
	}.bind(this), 3000);
	// bind 改变 定时器函数中 this 的指向
}

- Book Lists -