有没有办法在 JavaScript 中自定义/覆盖赋值操作?

发布于 2024-09-24 08:07:12 字数 465 浏览 0 评论 0原文

每次分配一个字符串时,我实际上想分配一个字符串对象,而不需要额外的代码。

这个 var foo = "bar";
变成 var foo = new String("bar");

基本上劫持了作业。


后续:
如果上述不可能,是否有一种方法可以对 string 变量类型而不是 String 对象进行原型设计?

正如 armando 所指出的,foo 将是一个字符串类型,但本质上是一个自定义的大批。如果能够为该类制作函数原型那就太好了。

Every time I assign a string, I'd actually like to assign a string object, without the extra code.

This var foo = "bar";
becomes var foo = new String("bar");

Basically hi-jacking the assignment.


Follow-up:
If the above is not possible is there a way to prototype the string variable type, rather than the String object?

As pointed out by armando, the foo would be a string type, but is essentially a customized array. It would be nice to be able to prototype functions to that class.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

坚持沉默 2024-10-01 08:07:12
  1. 不,这是不可能的。
  2. 如果可能的话,您真的不会想这样做,至少在全球范围内不会这样做。

  • 字符串变量类型没有对象所具有的所有额外开销。
    注意:创建的字符串数组(在您的例子中,foo)将具有其他属性(例如foo.length
  • 。性能打击
  1. No this is not possible
  2. If it was possible, you really would not want to do this, at least not globally.

  • The string variable type does not have all the extra overhead that an object does.
    Note: the string array that is created (in your case, foo) would have other properties (eg foo.length)
  • Objects come at a performance hit
踏雪无痕 2024-10-01 08:07:12

这不完全是您正在寻找的内容,但您可能想看看 Overriding赋值运算符 in JS

It's not quite what you're looking for, but you may want to look at Overriding assignment operator in JS

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文