this 使用問(wèn)題
大部分開(kāi)發(fā)者都會(huì)合理、巧妙的運(yùn)用 this
關(guān)鍵字。
初學(xué)者容易在 this
指向上犯錯(cuò),如下面這個(gè) Vue 組件
:
<div id="app"></div>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.min.js"></script>
<script>
// 發(fā)送post請(qǐng)求
const post = (cb) => {
// 假裝發(fā)了請(qǐng)求并在200ms后返回了服務(wù)端響應(yīng)的內(nèi)容
setTimeout(function() {
cb([
{
id: 1,
name: '小紅',
},
{
id: 2,
name: '小明',
}
]);
});
};
new Vue({
el: '#app',
data: function() {
return {
list: [],
};
},
mounted: function() {
this.getList();
},
methods: {
getList: function() {
post(function(data) {
this.list = data;
console.log(this);
this.log(); // 報(bào)錯(cuò):this.log is not a function
});
},
log: function() {
console.log('輸出一下 list:', this.list);
},
},
});
</script>
這是初學(xué) Vue
的同學(xué)經(jīng)常碰到的問(wèn)題,為什么這個(gè) this.log()
會(huì)拋出異常,打印了 this.list
似乎也是正常的。
這其實(shí)是因?yàn)閭鬟f給 post
方法的回調(diào)函數(shù),擁有自己的 this,有關(guān)內(nèi)容可以查閱 this章節(jié)。
不光在這個(gè)場(chǎng)景下,其他類(lèi)似的場(chǎng)景也要注意,在寫(xiě)回調(diào)函數(shù)的時(shí)候,如果在回調(diào)函數(shù)內(nèi)要用到 this
,就要特別注意一下這個(gè) this
的指向。
可以使用 ES6 的箭頭函數(shù)
或者將需要的 this 賦值給一個(gè)變量,再通過(guò)作用域鏈的特性訪(fǎng)問(wèn)即可:
<div id="app"></div>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.min.js"></script>
<script>
// 發(fā)送post請(qǐng)求
const post = (cb) => {
// 假裝發(fā)了請(qǐng)求并在200ms后返回了服務(wù)端響應(yīng)的內(nèi)容
setTimeout(function() {
cb([
{
id: 1,
name: '小紅',
},
{
id: 2,
name: '小明',
}
]);
});
};
new Vue({
el: '#app',
data: function() {
return {
list: [],
};
},
mounted: function() {
this.getList();
},
methods: {
getList: function() {
// 傳遞箭頭函數(shù)
post((data) => {
this.list = data;
console.log(this);
this.log(); // 報(bào)錯(cuò):this.log is not a function
});
// 使用保留 this 的做法
// var _this = this;
// post(function(data) {
// _this.list = data;
// console.log(this);
// _this.log(); // 報(bào)錯(cuò):this.log is not a function
// });
},
log: function() {
console.log('輸出一下 list:', this.list);
},
},
});
</script>
這個(gè)問(wèn)題通常初學(xué)者都會(huì)碰到,之后慢慢就會(huì)形成習(xí)慣,會(huì)非常自然的規(guī)避掉這個(gè)問(wèn)題。