普通函式:this 永遠指向呼叫它的物件,new的時候,指向new出來的物件,
箭頭函式:箭頭函式沒有自己的 this,當在內部使用了 this時,它會指向最近一層作用域內的 this,
//例1
var obj = {
name: 'latency',
sayName: function(){
console.log('name:',this.name);
}
}
obj.sayName() //name: latency
例1:呼叫sayName()的是obj,所以this指向obj,
//例2
var name = 'cheng';
var obj = {
name: 'latency',
sayName: function(){
return function(){
console.log('name:',this.name);
}
}
}
obj.sayName()() //name: cheng
例2:obj調sayName方法后,回傳的是一個閉包,而真正調這個閉包的是windows物件,所以其this指向window物件,
//例3
var obj = {
name: 'latency',
sayName: function(){
return () => {
console.log('name:', this.name);
}
}
}
obj.sayName()() //name: latency
例3:箭頭函式沒有自己的 this,當在內部使用了 this時,它會指向最近一層作用域內的 this,因為有return所以出了sayName()當前作用域,所以它會指向最近一層作用域內的 this即obj,
//例4
var name = 'cheng';
var obj = {
name: 'latency',
sayName: () => {
console.log('name:', this.name)
}
}
obj.sayName() //name: cheng
例4:由于sayName()整個函式就是一個箭頭函式,沒有自己的this,所以this指向的最近一層作用域內的this,也就是window物件,這種情況下,就不適合用箭頭函式來實作了,
//例5
var obj = {
name: 'latency',
sayName: function(){
return () => {
return () => {
return () => {
console.log("name:", this.name);
};
};
};
}
}
obj.sayName()()()() //name: latency
例5:自己練習吧!
參考鏈接:https://blog.csdn.net/latency_cheng/article/details/80022066
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/117361.html
標籤:JavaScript
上一篇:JS原型鏈常見面試題分析
