这不是开玩笑的设置,我真的在问。
Douglas Crockford is fond of saying在 javascript 原型(prototype)面向对象语言中不需要 new
。
他解释说,添加 new
只是为了给来自基于类(即“经典”)面向对象编程语言的人们一定程度的舒适感:
JavaScript, We Hardly
new
YaJavaScript is a prototypal language, but it has a
new
operator that tries to make it look sort of like a classical language. That tends to confuse programmers, leading to some problematic programming patterns.You never need to use
new Object()
in JavaScript. Use the object literal{}
instead.
好的,很好:
新的
不好的{}
很好
然后评论者Vítor De Araújo pointed out that the two are not the same .他举了一个例子来说明 string
不像 object
:
A string object and a string value are not the same thing:
js> p = "Foo" Foo js> p.weight = 42 42 js> p.weight // Returns undefined js> q = new String("Foo") Foo js> q.weight = 42 42 js> q.weight 42
The string value cannot have new properties. The same thing is valid for other types.
string
不是 object
是怎么回事?我是否将 javascript 与其他一些语言混淆了,在其他语言中一切都是对象?
最佳答案
“一切皆对象”...这是该语言中存在的重大误解之一。
不是 一切都是对象,还有我们所说的原始值,它们是字符串、数字、 bool 值、null 和 undefined .
没错,字符串是一个原始值,但您可以像访问对象一样访问从String.prototype
继承的所有方法。
属性(property)accessor operators (点和括号表示法),暂时将字符串值转换为 String 对象,以便能够访问这些方法,例如:
"ab".charAt(1); // "b"
幕后发生的事情是这样的:
new String("ab").charAt(1); // "b", temporal conversion ToObject
与其他原始值(例如 Boolean
和 Number
)一样,有对象包装器,它们只是包含原始值,如您的示例所示:
var strObj = new String("");
strObj.prop = "foo";
typeof strObj; // "object"
typeof strObj.prop; // "string"
使用原语时:
var strValue = "";
strValue.prop = "foo";
typeof strValue; // "string"
typeof strValue.prop; // "undefined"
发生这种情况是因为上面第二行的属性访问器再次创建了一个新的时间对象,如:
var strValue = "";
new String(strValue).prop = "foo"; // a new object which is discarded
//...
关于javascript - Javascript 字符串怎么不是对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59446773/