javascript - 在对象原型(prototype)上附加下划线,坏主意?

标签 javascript underscore.js ecmascript-5

常识是,仅仅因为您可以扩充原生类型,并不意味着您应该

扩充原生类型原型(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/

相关文章:

javascript - 有没有办法记录 Node 获取请求?

javascript - HTML5 可拖动 ='false' 在 Firefox 浏览器中不起作用

javascript - bootstrap 选项卡单击 preventDefault 不起作用

javascript - $parsers 和 $formatters 只被调用一次,而不是在每次值更新时调用

javascript - var 关键字的用途是什么,我应该什么时候使用它(或省略它)?

javascript - 使用流优化联合类型中的可选属性

javascript - 将 View 中的项目添加到数组 (backbone.js)

Javascript - 生成适合固定总和的舍入整数数组

javascript - 如何使用 javascript 或 Lodash 从多个对象创建单个对象

Javascript 条件正则表达式 if-then-else