我对Javascript的原型属性感到困惑。见下面的代码。
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我理解,当我们使用上面的{}或构造函数(new ())创建对象时,它是从Object.prototype继承的。这就是为什么console.log(s1 instanceof String); // Outputs: true,因此我们能够在s1上调用toString()的原因。但我对var x = "someString" or var x = something.的情况很困惑
耽误您时间,实在对不起。
发布于 2015-09-26 13:57:50
string原语值(如"hello world")与String对象之间存在差异。基本类型--字符串、数字、布尔--不是对象。
当原语值像对象一样使用时,使用.或[]运算符时,运行时通过相应的构造函数(String、Number、Boolean)隐式包装对象中的值。基元值没有属性,但是由于自动包装,您可以执行以下操作
var n = "hello world".length;而且起作用了。
https://stackoverflow.com/questions/32797939
复制相似问题