我刚刚进入 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/