https://vuejs.org/v2/guide/co...
尝试还原情景: 一个构造函数, 传入相同参数, 创建多个实例
使用对象时
const myself = { firstname: 'wei', lastname: 'chen'}function TestFunc(obj){ this.person = obj}const instance1 = new TestFunc(myself)const instance2 = new TestFunc(myself)instance1.person.firstname = 'li'instance2.person.lastname = 'siyuan'myself.firstname = 'random'console.log(myself)console.log(instance1, instance2)
打印结果如下:
由上图可以看出, myself, instance1.person, instance2.person 指向的是同一个对象, 一变都会变. 根本原因是 js 对于对象是传引用的
同样地, 如果 Vue 中组件的 data 选项是对象, 那么实例 $data 指向的是同一个对象
使用函数时
function myself(){ return { firstname: 'wei', lastname: 'chen' }}function TestFunc(func){ this.person = func()}const instance1 = new TestFunc(myself)const instance2 = new TestFunc(myself)instance1.person.firstname = 'li'instance2.person.lastname = 'siyuan' console.log(instance1, instance2)console.log(myself())
打印结果如下:
由上图可以看出, 通过函数生成了不同的对象, 属性的改变不会再互相影响
function myself(){ return { firstname: 'wei', lastname: 'chen' }}const obj1 = myself()const obj2 = myself()console.log(obj1 == obj2) //false
Vue-组件的data属性为什么必须是函数? https://axiu.me/coding/why-vu...