函式中的this
在標準函式中,this參考的是把函式當成方法呼叫的背景關系物件,這時候通常稱其為this值(在網頁的全域背景關系中呼叫函式時,this指向window),
這個this值到底參考哪個物件,必須到函式被呼叫的時候才能確定,因此這個值在代碼執行程序中可能會變,
箭頭函式中的this
在箭頭函式中,this參考的是定義箭頭函式的背景關系,也可以說this值取決于該函式外部非箭頭函式的this值,且不能通過call(), apply(), bind() 方法來改變this值,
類中的this
類的宣告基本上還是基于自定義型別宣告的語法糖
class Person {
constructor(name) {
this.name = name;
}
getName() {
return this.name
}
}
typeof Person // function
等價于
function Person(name) {
this.name = name
}
Person.prototype.getName = function() {
return this.name
}
class中的方法,除了靜態方法,都是原型鏈上的,其中的name屬性則是自由屬性,不會出現在原型上,且只能在類的建構式或方法中創建,
因為方法是原型上的,所以函式中的this指向的背景關系就是實體物件,
const joey = new Person('joey')
joey.getName();
//getName中的this,指向的是joey實體,
在react中
class ButtonDemo extends PureComponent {
componentDidMount() {
console.log(this); 實體
console.log(typeof this); object
console.log(this instanceof ButtonDemo); true
}
hello() {
console.log(this); // undefined
}
render() {
return (<Button block={true} onClick={this.hello}>Click Me</Button>);
}
}
在react中,hello雖然是ButtonDemo實體的方法,但是呼叫的背景關系是在Button的onClick方法中,這邊的背景關系指向已經不是ButtonDemo的實體了,最終點擊后列印出來的this是undefined,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/501750.html
標籤:其他
上一篇:ahooks 中那些控制“時機”的hook都是怎么實作的?
下一篇:axios實作無感重繪
