javascript - 如果在使用后删除它,将方法附加到 String 是否安全?

标签 javascript prototype

我刚刚进入 Node.js 和 CommonJS 模块,我正在尝试扩展 String 对象而不乱扔我的应用程序的其余部分,并提供一个看起来很干净的方法。

我想知道,是否可以将一个方法附加到全局 String 对象,然后在文件底部,删除它?

例如:

// hasCondition.js

String.prototype.has = function(regex) {
    return regex.test(this);
};
exports.removeMethod = function () {
    delete String.prototype.has;
};

.

// someFile.js

var has = require('./hasCondition');
console.log(  "foo bar baz".has(/baz/)  );
has.removeMethod();
console.log(  "foo bar baz".has(/baz/)  );

>>> true
>>> Object foo bar baz has no method 'has'

最佳答案

如果您不想弄乱 String 空间,您可以创建一个新的 Object,其原型(prototype)来自 String。然后,在其原型(prototype)中为该对象分配 has 方法。它不会传播回字符串。

这样,你就封装了它。当然,您添加了另一个间接层,但它已经是一个 design pattern .

如果您只是担心 has 以后会被保存在某个地方,它可能不会被保存。 即使您使用添加的 has 方法从 String 生成子对象,当它被删除时,它也会从任何继承中删除。

例子(让我们假设断言已定义):

function Str1() {}
Str1.prototype = new String()
String.prototype.has = function(t) { /* code here */ }
var x = new Str1()
assert(x.has)

function Str2() {}
Str2.prototype = new Str1()

var y = new Str2()
assert(y.has)

delete String.prototype.has

assert(typeof x.has === "undefined")
assert(typeof y.has === "undefined")

关于javascript - 如果在使用后删除它,将方法附加到 String 是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14543007/

相关文章:

javascript - 为什么重新分配 Object.prototype 不起作用?

javascript - html/Javascript : Add Attribute to an HTML Control

javascript - 我无法使用 rowReorder 替换 dataTable 中的行

javascript - 谷歌地图 - 未捕获的类型错误 : Cannot set property 'position' of undefined

javascript - 我可以在 D3 气泡图中强制气泡大小比率吗?

Javascript 继承调用行为

javascript - 函数未分配给 Chrome 中另一个函数的原型(prototype)

JavaScript – 从另一个原型(prototype)函数调用原型(prototype)函数?

javascript - Function.prototype.method 中的 return this 有什么作用?

php - 切换语言 javascript/php