本文是深入淺出 ahooks 源碼系列文章的第五篇,該系列已整理成文檔-地址。覺得還不錯,給個 star 支持一下哈,Thanks。 本文來探索一下 ahooks 是怎麼封裝 React 的一些執行“時機”的? Function Component VS Class Component 學習類似 R ...
函數中的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。