字符串对象与文字-修改原型吗? [英] String object versus literal - modifying the prototype?

查看:64
本文介绍了字符串对象与文字-修改原型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么在字符串文字的原型中添加方法似乎可行,但是添加属性却不可行?我在玩有关

I'm wondering why it seems that adding a method to the prototype of a string literal seems to work, but adding a property does not? I was playing with ideas in relation to this question, and have the following code:

String.prototype._str_index1 = 0;
String.prototype._str_reset = function() {
    this._str_index1 = 0;
};
String.prototype._str_substr = function(len) {
  var ret = this.substr(this._str_index1, len);
  this._str_index1 = this._str_index1 + len;
  return ret;
};

var testString = new String('Loremipsumdolorsitamet,consectetur');
log(testString._str_substr(5));
log(testString._str_substr(4));
​

这很好.但是,如果我将倒数第三行更改为:

This works fine. If however I change the third-last line to:

var testString = 'Loremipsumdolorsitamet,consectetur';

...似乎,尽管方法 _str_substr 存在并且可以在字符串文字上调用,但是属性 _str_index1 的值始终为0.

...it seems that although the method _str_substr exists and is callable on the string literal, the value of the property _str_index1 is always 0.

怎么了?

推荐答案

每次尝试调用 String 方法时,字符串基元都会转换为瞬态 String 对象.code>对象(JavaScript引擎在必要时在内部将字符串基元转换为 String 对象).该函数返回后, String 对象被(毫不干扰地)转换回字符串基元(在幕后),并返回该新基元(并且大部分时间都分配给了变量);每次调用 String 对象的方法.

The string primitive is converted to a transient String object every time you try to invoke a method of the String object (the JavaScript engine internally converts a string primitive to a String object when necessary). After this function returns, the String object is (unobtrusively) converted back to a string primitive (under the hood) and this new primitive is returned (and most of the time assigned to a variable); every time a method of the String object is invoked.

因此,每次调用 testString._str_substr 后, _str_index1 随该对象和一个新对象(带有重置的 _str_index1 )而被丢弃.)是在再次调用 _str_substr 时创建的.

So, after each invocation of testString._str_substr, _str_index1 is thrown away with the object and a new object (with a reset _str_index1) is created when _str_substr is called again.

另请参见 MDC :

由于JavaScript自动在字符串基元和String对象之间转换,因此可以在字符串基元上调用String对象的任何方法.JavaScript自动将字符串基元转换为临时String对象,调用该方法,然后丢弃该临时String对象.

Because JavaScript automatically converts between string primitives and String objects, you can call any of the methods of the String object on a string primitive. JavaScript automatically converts the string primitive to a temporary String object, calls the method, then discards the temporary String object.

这篇关于字符串对象与文字-修改原型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆