在非箭頭函數(shù)下斋陪, this 指向調(diào)用其所在函數(shù)的對象
箭頭函數(shù)導(dǎo)致this總是指向函數(shù)定義生效時所在的對象
1.png
以前這種情況下,根據(jù)“箭頭函數(shù)”的this官觅,總是指向定義時所在的對象,而不是運行時所在的對象。
這句話公荧,我會認(rèn)為箭頭函數(shù)的this指向foo,但這是錯的同规。
為什么呢循狰,關(guān)鍵在于”定義時“三個字。我們會理所當(dāng)然把它和“書寫時”等價捻浦,但其實這是錯的晤揣,注意是函數(shù)定義生效時。
<body>
<h1> this is a header</h1>
<div class="hh">hh</div>
<div class="hhh">hhh</div>
<div class="hhhh">hhhh</div>
<div class="hhhhh">hhhhh</div>
</body>
<script>
window.onload=function(){
var $=(selector)=>{
return document.querySelector(selector);
}
function zzh(){
this.id=1;
}
zzh.prototype={
constructor:zzh,
h:function(){
console.log(this); //zzh {id: 1}
},
hh:function(){
$('.hh').onclick=function(){
console.log(this); //<div class="hh">hh</div>
}
},
hhh:function(){
var self=this;
$('.hhh').onclick=function(){
console.log(this); //<div class="hhh">hhh</div>
console.log(self);//zzh {id: 1}
}
},
hhhh:function(){
$('.hhhh').onclick=()=>{console.log(this)} //zzh {id: 1}
},
hhhhh:function(){
$('.hhhhh').onclick=function(){
console.log(this);
}.bind(this); //zzh {id: 1}
}
}
var z1=new zzh();
z1.h();
z1.hh();
z1.hhh();
z1.hhhh();
z1.hhhhh();
}
</script>
箭頭函數(shù)中的this繼承外圍作用域
let person = {
name: "gard",
say: () => {
console.log(this);
console.log(this.name);
}
};
person.say();
this的值為window或global對象朱灿,this.name的值為undefined或""(空字符串)昧识。
隨手記
當(dāng)我們new 一個對象的時候到底干了什么?
var person1=new Person();
其實就是下面三步
var person1 = {};
person1.__proto__ =Person.prototype;
Person.call(person1);
第一行盗扒,我們創(chuàng)建了一個空對象person1跪楞。
第二行,我們將這個空對象的__proto__屬性指向了Person函數(shù)對象prototype成員對象侣灶。
第三行甸祭,我們將Person函數(shù)對象的this指針替換成person1,然后再調(diào)用Person函數(shù)褥影。