常识是,仅仅因为您可以扩充原生类型,并不意味着您应该。
扩充原生类型原型(prototype)始终不是一个好主意,唯一的异常(exception)是 ECMAScript 规范中的 polyfill 行为。
在我们的项目中,我们经常使用下划线,我想知道,为什么不直接在我们的对象上使用它提供的 OOP 样式?
var _ = require('underscore');
Object.defineProperty( Object.prototype, '_', {
get: function() {
return _(this);
}
});
这使我们能够像这样直接使用下划线方法,而不必决定在我们想要使用它的任何地方都需要该库,而只需知道它在那里并在适当的时候标准化使用下划线功能。
[1, 2, 3]._.contains(3); // true
var funcOnce = function() {
console.log("hello");
}._.once();
funcOnce(); // "hello"
funcOnce(); //
{one: 1, two: 2, three: 3}._.keys(); // ['one', 'two', 'three']
我相信我已经通过仅修改 native 对象的单个(可能无用的 _
?)属性来限制损害的范围。
假设 Object
中从未引入原生 _
属性,你能看出这将如何影响我们开发应用程序吗?
最佳答案
Can you see how this will come back to bite us in developing our application, assuming there is never a native
_
property introduced in Object?
是的。当你有 avoided that the property shows up in for in
loops ,您确实忘记提供二传手。这肯定会猎杀你:
// let's start with this
Object.defineProperty( Object.prototype, '_', {
get: function() {
return "sorry";
}
});
// now what do you expect the following statements to do?
> var x = {}; "_" in x;
true // meh, obvious
> var x = {_:"works"}; x._
"works" // this is hijackable in older browsers!
> var x = {}; x._ = "works"; x._
"sorry" // well…
(function(){"use strict"; var x={}; x._ = "works"; return x._; }())
unhandled TypeError: "Invalid assignment in strict mode" // ooops!
> _
"sorry" // ah, window._ inherits from Object.prototype as well
> _ = "works"; _
"sorry" // and prevents even simple global variable assignments
关于javascript - 在对象原型(prototype)上附加下划线,坏主意?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24922049/