前言
我們需要先復習下原型鏈的知識,其實這個問題取決于 js ,而并非是 vue ,
function Component(){
this.data = https://www.cnblogs.com/chengxuyuanaa/p/this.data
}
Component.prototype.data = https://www.cnblogs.com/chengxuyuanaa/p/{
name:'jack',
age:22,
}
復制代碼
首先我們達成一個共識(沒有這個共識,請補充下 js 原型鏈部分的知識):
- 實體它們建構式內的this內容是不一樣的,
- Component.prototype ,這類底下的方法或者值,都是所有實體公用的,
解開疑問
基于此,我們來看看這個問題:
function Component(){
}
Component.prototype.data = https://www.cnblogs.com/chengxuyuanaa/p/{
name:'jack',
age:22,
}
var componentA = new Component();
var componentB = new Component();
componentA.data.age=55;
console.log(componentA,componentB)我是08年出道的高級前端老鳥,有問題或者交流經驗可以進我的扣扣裙 519293536 我都會盡力幫大家哦
此時,componentA 和 componentB data之間指向了同一個記憶體地址,age 都變成了 55, 導致了問題!
接下來很好解釋為什么 vue 組件需要 function 了:
function Component(){
this.data = https://www.cnblogs.com/chengxuyuanaa/p/this.data()
}
Component.prototype.data = https://www.cnblogs.com/chengxuyuanaa/p/function (){
return {
name:'jack',
age:22,
}
}
var componentA = new Component();
var componentB = new Component();
componentA.data.age=55;
console.log(componentA,componentB)
復制代碼
此時,componentA 和 componentB data之間相互獨立, age 分別是 55 和 22 ,沒有問題!
總結
自己突然對這個問題懵逼,不過事后想了想還是自己基礎知識忘得太快,以前學習 js 的時候,最基礎的:建構式內和原型之間的區別都模糊了,想不到 vue 這個小問題讓我溫故而知新了一次,
本文的文字及圖片來源于網路加上自己的想法,僅供學習、交流使用,不具有任何商業用途,著作權歸原作者所有,如有問題請及時聯系我們以作處理
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/67744.html
標籤:JavaScript
