字符串不是对象,为什么它们有属性? [英] Strings are not object then why do they have properties?

查看:118
本文介绍了字符串不是对象,为什么它们有属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这样的代码:

var str = "Hello StackOverflow !";
alert(typeof str);

给我字符串作为结果。这意味着字符串不是对象,那么为什么我们有字符串 str 的属性,如 str.substring str.indexOf等?
当我将属性设置为

gives me string as result. This means strings are not objects, then why do we have properties of a string str like str.substring, str.indexOf etc.? Also when i set property to it as

str.property =自定义属性已设置; 并尝试获取此警报(str.property),它给了我 undefined 。为什么?

str.property = "custom property is set"; and trying to get this alert(str.property), it gives me undefined. Why?

推荐答案

像Hello这样的字符串不是JavaScript中的对象,但是在像

A string like "Hello" is not an object in JavaScript, but when used in an expression like

"Hello".indexOf(2)

从构造函数 String 派生的新对象包含字符串Hello。并且 indexOf String.prototype 的属性,所以事情按预期工作,即使有很多魔法on。

A new object derived from the constructor function String is produced wrapping the string "Hello". And indexOf is a property of String.prototype so things work as expected, even though there is a lot of magic going on.

在以下情况中

> var s = "xyz"; s.prop = 1; console.log(s.prop);
undefined

您看到的原因 undefined 是:


  1. 变量 s 的值是一个原始字符串

  2. s.prop = 1 中,名为 prop 的属性是分配给一个新的匿名包装器对象。

  3. 在上面的第三个语句中,创建了另一个新对象来包装原语 s 。这与第二个语句中的包装器对象不同,并且它没有 prop 属性,因此 undefined 根据基本的JavaScript规则询问其值时生成。

  1. The variable s is given a value which is a primitive string
  2. In s.prop = 1 and property named prop is assigned to a new, anonymous wrapper object.
  3. In the third statment above, another new object is created to wrap the primitive s. That is not the same wrapper object as in the second statement, and it does not have a prop property, so undefined is produced when asking for its value according to the basic JavaScript rules.

这篇关于字符串不是对象,为什么它们有属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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