是否可以向String
实例添加方法,例如
x = "123"
x.method = function() { console.log("test") }
x.method()
是否可以向String
实例添加方法,例如
x = "123"
x.method = function() { console.log("test") }
x.method()
是的,你可以做到。但是,你需要首先将字符串基本类型转换为字符串实例:
x = new String("123");
x.method = function() { console.log("test") };
x.method();
x.method = ...;
...从变量x
中检索到字符串原始值并提升为字符串实例,然后添加了方法,但由于字符串实例没有存回x
变量,当您尝试调用该方法时它不在那里。(是的,这很反直觉。)
通过在上述代码中使用new String(...)
,实际上我获得了字符串实例并将其存储在x
中。然后,因为它是一个真正的对象,我可以为它添加属性。
您还可以像下面这样向String.prototype
添加方法:
String.prototype.capitalize = function() {
return this.substring(0, 1).toUpperCase() + this.substring(1);
};
console.log("testing".capitalize()); // "Testing"
String.prototype
时出现任何问题,但是我却看到了人们增强Array.prototype
(因为人们坚持使用错误使用for-in
),以及Object.prototype
时出现了问题。字符串和数字是自动装箱的原始类型,这意味着当您对它们执行面向对象操作时,它们会被转换为“String”和“Number”类,但随后立即取消装箱。
您的代码评估结果为:
x = "123"
(new String(x)).method = function() { console.log("test") }
(new String(x)).method() // Error
你的第二个调用失败是因为你正在处理一个完全不同的字符串对象。正如T.J.所说,你可以通过将x
变成一个字符串对象来解决这个问题,但这不是一个常见或推荐的做法。
你可以通过在String.prototype
中添加方法来扩展所有字符串:
x = "123"
String.prototype.method = function() { console.log("test") }
x.method()
这个调用与(new String(x)).method()
的求值方式相同,但由于该方法存在于原型中,因此将调用它。
this
,它将是封装的 String
而不是基本类型的 string
,但大多数操作都是相同的。例如:String.prototype.parseInt = function () { return parseInt(this); }
- Brian Nickelthis.toString()
。 - Brian Nickel您可以使用ECMA5定义新属性
Object.defineProperty(String.prototype, "test", {
value: function test() { console.log('test:',this) },
configurable: true,
enumerable: false,
writeable: true
});
查看完整答案: 不修改原型扩展核心类型
x = "123"
改为x = new String("123")
,是可以的,但这不是一个好的做法。 - Fabrício MattéString.prototype
中,但正如其他人所说,修改原生对象的原型并不是一个好习惯。String.prototype.method = function () { console.log(this); }
- plalxString.prototype
会有任何问题),但不是针对个别实例的。 - T.J. Crowder