Closed Haixing-Hu closed 9 years ago
I looked into the source code of Vue, and found that the error occurs in the following function at the line 50 of vue/src/instance/scope.js
:
exports._initData = function () {
var propsData = this._data
var optionsDataFn = this.$options.data
var optionsData = optionsDataFn && optionsDataFn()
if (optionsData) {
this._data = optionsData
for (var prop in propsData) {
if (
this._props[prop].raw !== null || // HERE
!optionsData.hasOwnProperty(prop)
) {
optionsData.$set(prop, propsData[prop])
}
}
}
var data = this._data
// proxy data on instance
var keys = Object.keys(data)
var i, key
i = keys.length
while (i--) {
key = keys[i]
if (!_.isReserved(key)) {
this._proxy(key)
}
}
// observe data
Observer.create(data, this)
}
It seems that there are the following problems:
_initData()
function, the VM's _props
has not been defined. _initData()
function, the VM's _data
is an empty object, therefore the propsData
is an empty object; but if something was added into the Object.prototype
, the for prop in propsData
will loop with the names of the properties or functions added into the prototype of Object, which is not what we want. In fact I cannot understand the function of the for loop. If I comment it, the Vue still works without any error.
@yyx990803, could you please explain the function of the for prop in propsData
loop? Thank you in advance.
You should never, ever add an enumerable property to Object.prototype. It'll break any code that uses the for...in loop.
@yyx990803 , My project use a third part library which defines some function to Object.prototype. And I think the for..in loop should work together with the Object.hasOwnProperty() function to overcome the problem.
The test code is as follows:
When loading this page in the browser, I got the following error message:
If I comment the definitnion of
Object.prototype.test
, the error disappeared.But in my project, I have a third part library which add some functions to the Object.prototype.