JavaScript - 为什么我不能向“string”添加新属性宾语? [英] JavaScript - Why can't I add new attributes to a "string" object?

查看:67
本文介绍了JavaScript - 为什么我不能向“string”添加新属性宾语?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试过JavaScript并注意到这个奇怪的事情:

I've experimented with JavaScript and noticed this strange thing:

var s = "hello world!";
s.x = 5;
console.log(s.x); //undefined

JavaScript中的每种类型的变量都是从object继承的。所以应该可以为每个对象添加新属性。

Every type of variable in JavaScript is inherited from object. So it should be possible to add new attributes to every object.

我是否误解了错误?

推荐答案

JavaScript中的字符串不是 String 的实例。如果你做 new String('my string')那么它就是。否则它是一个原语,当你在其上调用方法时,它会动态转换为 String 对象。如果你想获得字符串的值,你需要调用 toString(),如下所示:

A string in JavaScript isn't an instance of String. If you do new String('my string') then it will be. Otherwise it's a primitive, which is converted to a String object on the fly when you call methods on it. If you want to get the value of the string, you need to call toString(), as shown below:

var s = new String("hello world!");
s.x = 5;
console.log(s.x); //5
console.log(s); //[object Object]
console.log(s.toString()); //hello world!

这篇关于JavaScript - 为什么我不能向“string”添加新属性宾语?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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