我对Javascript的prototype属性感到困惑。
参见下面的代码。

var s = 12;
var s1 = new String();

console.log(s.constructor);  // Outputs: Number() { [native code] }
console.log(s instanceof String); // Outputs: false
console.log(s instanceof Object); // Outputs: false
//console.log(toString() in s);
console.log(s.isPrototypeOf(Object)); // Outputs: false
//console.log(s.prototype.isPrototypeOf(Object));

console.log(s.hasOwnProperty ("toString")); // Outputs: false

console.log(s.toString()); // // Outputs: 12
// My Question is how does toString() function is been called, where does it falls int the prototype chain. Why is it not showing undefined.

console.log(s1.constructor); // Outputs: Number() { [native code] }
console.log(s1 instanceof String); // Outputs: true


我了解,当我们使用{}或上面的构造函数(新String())创建对象时,该对象继承自Object.prototype。这就是为什么console.log(s1 instanceof String); // Outputs: true从而可以在s1上调用toString()的原因。但是我对var x = "someString" or var x = something.的情况感到困惑

谢谢你的时间。

最佳答案

字符串原始值(例如"hello world")和String对象之间存在区别。基本类型(字符串,数字,布尔值)不是对象。

当像对象一样使用原始值时,通过.[]运算符,运行时将通过相应的构造函数(StringNumberBoolean)将值隐式包装在对象中。原始值没有属性,但是由于自动包装,您可以执行以下操作

var n = "hello world".length;


而且有效。

10-04 23:01
查看更多