Augmenting Object.prototype breaks Dojo
I came across an issue which might be a bug, or it might just be the intended functionality. I'm using a thirdparty script that is built with Dojo. In my own app I augment the Function.prototype and the Object.prototype with (for my app) handy utility functions. Including the thirdparty script always resulted in an error.
Uncaught TypeError: Cannot set property _scopeName' of undefined
Uncaught TypeError: Cannot read property 'toString' of undefined
After a while I realized it might lie in the fact that I augmented these prototypes. The Function.prototypes seemed to have no ill effect. But as soon as I removed all of my Object.prototype methods it stopped throwing the error.
A simple test setup
<html lang="nl">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
Object.prototype.foo = function() {
console.log('bar');
}
</script>
<script src="//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js"></script>
</body>
</html>
Is this intended? And if so, would it not be better to then catch this error and throw a more meaningfull one?
Don't do that. :-)
You've added an enumerable property to Object.prototype
, which means it shows up on all objects (via inheritance) in for-in
loops and such:
// DON'T DO THIS (see text for why)
Object.prototype.foo = function() {
console.log("foo");
};
// Looping over an object
var obj = {
myOwnProperty: "bar"
};
for (var key in obj) {
snippet.log("obj['" + key + "']: " + obj[key]);
}
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
链接地址: http://www.djcxy.com/p/27246.html