Reputation: 884
I declared an extension method for objects by creating my own function. However, I do not call or import it anywhere. As a result, I get an exception. How can I fix this? I don't recall such behavior in VUE 2.
Object.prototype.mergeObjXXXX = function(obj2){
console.log(this);
console.log(obj2);
}
vue 3.5.13 vue-router: 4.5.0
main.js:38 TypeError: Cannot convert undefined or null to object
at Object.assign (<anonymous>)
at Object.mergeObjXXXX (ext.js:20:9)
at extractComponentsGuards (vue-router.js?v=ea680b7e:1465:32)
at vue-router.js?v=ea680b7e:2484:16
Upvotes: 1
Views: 34
Reputation: 222890
It's totally expected that modifying built-in object prototypes can cause problems at some point. It has been a bad practice for over than a decade for good reasons and marked as a serious problem by code analyzers.
The least thing that can be done to reduce the possibility of problems is to make mergeObjXXXX
non-enumerable:
Object.defineProperty(Object.prototype, 'mergeObjXXXX', {
value: function(obj2){...},
configurable: true
});
This results in non-enumerable, non-writable, configurable mergeObjXXXX
property and corresponds to other prototype method descriptors.
It's unknown what the exact cause is in this case, but this could be a fix here because the error potentially results from Vue router iterating enumerable properties with in
operator, which isn't a good practice either. A correct way to do this from that side would be to iterate own properties with Object.keys
instead, because this is the intention. That one piece of code does something that is not foreseen in another piece of code is the exact problem with polluting object prototypes and modifying globals for local purposes in general.
The proper fix would be to refactor the occurrences of obj.mergeObjXXXX(obj2)
to myHelpers.mergeObjXXXX(obj, obj2)
, this can be done with a simple regex replacement for the entire codebase. There's just no good justification for this these days.
Upvotes: 1