原文章:https://segmentfault.com/a/1190000023741737
this 的四种绑定方式
this 的指向并不是在创建的时候就可以确定的,在es5中,this 永远指向最后一个调用它的那个对象。
this 的四种绑定方式:隐式绑定、显式绑定、window 绑定、new 绑定。
隐式绑定
const user = {
name: 'Cherry',
age: 27,
getName() {
console.log(`Hello, my name is ${this.name}`)
}
}
user.getName() // Hello, my name is Cherry
调用user对象上的 getName 方法,会用到点(.),这就是隐式绑定,点左侧的对象就是 this 的引用,getName 方法内部 JavaScript 解释器把 this 变成了 user。使用对象来调用其内部的一个方法,该方法的 this 是指向对象本身的。
const user = {
name: 'Cherry',
age: 27,
getName() {
console.log(`Hello, my name is ${this.name}`)
},
mother: {
name: 'Susan',
getName() {
console.log(`Hello, my name is ${this.name}`)
}
}
}
user.getName() // Hello, my name is Cherry
user.mother.getName() // Hello, my name is Susan
从这段代码可以看出:this 永远指向最后调用它的那个对象。
显式绑定
通过 call 来设置函数执行上下文的 this 指向。
function getName () {
console.log(`Hello, my name is ${this.myName}`)
}
let user = {
myName: 'Cherry',
age: 27,
}
getName.call(user) // Hello, my name is Cherry
getName 函数内部的 this 已经指向了 user 对象。
window 绑定
function getName () {
console.log(`Hello, my name is ${this.myName}`)
}
let user = {
myName: 'Cherry',
age: 27,
}
getName(); // Hello, my name is undefined
如果想用 user 做上下文调用 getName,可以使用 .call 、.apply 或 .bind 。如果没有使用这些方法, JavaScript 会默认 this 指向 window 对象,window 对象中没有 myName 属性,所以会打印 'Hello,my name is undefined'。
new 绑定
每当用 new 调用函数时,JavaScript 解释器都会在底层创建一个全新的对象,并把这个对象当做 this。
function User (name, age) {
/*
JavaScript 会在底层创建一个新对象 `this`,它会代理不在 User 原型链上的属性。
如果一个函数用 new 关键字调用,this 就会指向解释器创建的新对象。
*/
this.name = name
this.age = age
}
const me = new User('Cherry', 27)
伪代码表示:
var me = new User("Cherry","27");
new User{
var object = {};
object.__proto__ = User.prototype;
var result = User.call(object,"Cherry","27");
return typeof result === 'object'? result : object;
}
new 的过程:
- 创建一个空对象 object;
- 将新创建的空对象的隐式原型指向其构造函数的显式原型;
- 使用 call 改变 this 的指向;
- 如果无返回值或者返回一个非对象,则将 object 返回作为新对象;如果返回值是一个新对象的话那么直接返回该对象。
所以 new 的过程其实是使用 call 改变了 this 的指向。
JavaScript 调用的对象默认指向了全局对象 window,例如在上下文中直接调用 fn(),此时是 window 在调用,所以 this 指向 window,如果使用严格模式的话,全局对象就是 undefined,这时在函数内部通过 this 访问某个属性,就会报错:Uncaught TypeError: Cannot read property 'name' of undefined。
var name = "window";
function fnA(){
var name = "Cherry";
function fnB(){
console.log(this.name); // window
}
//在A函数内部调用B函数
fnB();
}
//调用A函数
fnA();
嵌套函数中的 this 不会从外层函数中继承。在函数执行环境中使用 this 时,如果函数没有明显的作为非 window 对象的属性,而只是定义了函数,这个函数中的 this 仍然默认指向 window 对象。
var name = "window";
var user = {
name : null,
// name: "Cherry",
fn : function () {
console.log(this.name); // window
}
}
var f = user.fn;
f();
这里虽然把 user 的 fn方法赋值给变量 f 了。但是没有调用,最后 fn() 还是被 window 调用的,所以 this 指向的也就是 window。
改变 this 的指向
- 使用 ES6 的箭头函数
- 在函数内部使用 _this = this
- 使用 apply、call、bind
- new 实例化一个对象
箭头函数
所有的箭头函数都没有自己的 this,都指向外层。
箭头函数的 this 总是指向所在函数运行时的 this。
- 函数体内的 this 就是定义时所在的对象,而非调用时所在的对象,和普通函数相反。
- 箭头函数无法用作构造函数,即不能使用 new 调用。
- 不能使用 arguments 对象,函数中不存在这个对象。
- 不可使用 yield 命令,即无法用作 Generator 函数。
在函数内部使用 _this = this
var name = "window";
var user = {
name : "Cherry",
fn1: function () {
console.log(this.name)
},
fn2: function () {
var _this = this;
setTimeout( function() {
_this.fn1()
},100);
}
};
user.fn2() // Cherry
使用 apply、call、bind
使用 apply()
var user = {
name: "Cherry",
fn1: function() {
console.log(this.name)
},
fn2: function() {
setTimeout(function () {
this.fn1()
}.apply(user), 100);
}
};
user.fn2() // Cherry
使用 call()
var user = {
name: "Cherry",
fn1: function() {
console.log(this.name)
},
fn2: function() {
setTimeout(function () {
this.fn1()
}.call(user), 100);
}
};
user.fn2() // Cherry
使用 bind()
var user = {
name: "Cherry",
fn1: function() {
console.log(this.name)
},
fn2: function() {
setTimeout(function () {
this.fn1()
}.bind(user)(), 100);
}
};
user.fn2() // Cherry
apply 和 call 的区别
其实 apply 和 call 基本类似,他们的区别只是传入的参数不同。
apply() 的使用方法:
var user ={
name: "Cherry",
fn: function(a,b) {
console.log(a + b)
}
}
var newUser = user.fn;
newUser.apply(user,[1,2]) // 3
call() 的使用方法:
var user ={
name: "Cherry",
fn: function(a,b) {
console.log(a + b)
}
}
var newUser = user.fn;
newUser.call(user, 1, 2) // 3
bind 和 apply、call 区别
var user ={
name: "Cherry",
fn: function (a,b) {
console.log( a + b)
}
}
var newUser = user.fn;
newUser.bind(user,1,2)() // 3
bind 创建一个新的函数,必须要手动去调用。
- call 和 apply 是立即执行,bind 则是返回一个绑定了 this 的新函数,只有你调用了这个新函数才真的调用了目标函数。
- bind 函数存在多次绑定的问题,如果多次绑定 this,则以第一次为准。
- bind 函数实际上是显式绑定(call、apply)的一个变种,称为硬绑定。在 ES5 中提供了内置的方法 Function.prototype.bind。
function foo() {
console.log( this.name );
}
var obj1 = {
name: 'obj1'
};
var obj2 = {
name: 'obj2'
}
var fn = foo.bind(obj1).bind(obj2)
fn() // => 'obj1'
fn.call(obj2) // => 'obj1'
bind 函数只能绑定一次,多次绑定没用,绑定后的函数 this 无法改变,即使 call / apply 也不行,所以称为硬绑定。
绑定的优先级
new > 显式 > 隐式 > Window