关于 Javascript 属性和实例的问题
我自己不明白为什么示例中的 foo.bar
是 undefined
,你能解释一下吗?
var foo = "foo";
foo.bar = "baz";
console.log(foo.bar); // undefined
Q2:如何将属性和方法的引用添加到 String
实例 foo
中?
感谢帮助,谢谢。
-- 编辑 --
注意:问题是关于通用字符串实例,而不是字符串全局对象。因此,按照某人的建议使用“经典”原型并不是一种选择,因为这样每个 String 实例都会有一个名为 bar
的属性,而我只想增强某些实例。
I can't figure out myself why foo.bar
in the example is undefined
, could you explain?
var foo = "foo";
foo.bar = "baz";
console.log(foo.bar); // undefined
Q2: How do I add references to properties and methods to the String
instance foo
?
Help is appreciated, thanks.
-- EDIT --
Note: the question is about a generic String instance, not the String global object. So using "classic" prototyping as someone suggested is not an option, because this way every String instance would have a property called bar
, while I want to augment only certain instances.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这是 为什么我不能在 JavaScript 中向字符串对象添加属性?。
基本上,您正在创建一个字符串,这是 JavaScript 中的原始类型。
您无法向 JavaScript 中的基本类型添加属性。
This is a duplicate of Why can't I add properties to a string object in javascript?.
Basically, you're creating a string, and this is a primitive type in javascript.
You cannot add properties to primitive types in javascript.
通过使用
foo
的真实 String 对象:By using a real String object for
foo
:foo.bar = "baz";
与undefined = "baz";
相同,您可以使用字符串的原型向其添加函数;
foo.bar = "baz";
is the same asundefined = "baz";
You can add functions to string by using it's prototype;
当您指定 var foo = "foo"; 时您要求将 foo 解释为字符串。字符串只能将文字作为值。它不能有任何其他子属性。 (只需将此逻辑扩展到您知道的任何其他面向对象编程语言,它就会变得更加清晰)。相反,你可以做这样的事情。
When you specified var foo = "foo"; you are asking foo to be interpreted as a string. String can only have a literal as a value. It cannot have any other sub-properties. ( just extend this logic to any other oo programming language you know and it will become clearer). Instead you could do something like this.
您正在谈论“原型设计”,即向 JavaScript 中的对象添加自定义属性的能力。
这是关于原型制作的优秀而简洁的教程:
http://www.javascriptkit.com/javatutors/proto.shtml
You're talking about "prototyping", which is the ability to add custom properties to objects in javascript.
This is an excellent and concise tutorial on prototyping:
http://www.javascriptkit.com/javatutors/proto.shtml
要扩展 String 类,请修改其原型:
在您的问题中,您正在修改 String 类的实例而不是 String 类本身。
To extend the String class, modify its prototype:
In your question, you were modifying an instance of the String class instead of the String class itself.