今天测试一段代码的时候发现:
var str1 = 'hello world'
console.log(str1 instanceof String) // 输出false
console.log(str1.__proto__ === String.prototype) // 输出true
对于这个结果感到很奇怪, 我以为是我对instanceof理解错了。 后来上MDN查了一下。 看了一下发现自己没有记错。 原文是这样的:
The instanceof operator tests whether an object has in its prototype chain the prototype property of a constructor.
我想问的是, 为什么这两个结果不同呢?
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
var str1 = "string"并不是一个String的一个instance,是一种primitive data type,而且它本身没有任何method,只不过你调用任何String的method的时候,会有一个auto-boxing的过程。详情可以看stckoverflow的这个解答。当 String() 和运算符 new 一起作为构造函数使用时,它返回一个新创建的 String 对象,存放的是字符串 s 或 s 的字符串表示。
当不用 new 运算符调用 String() 时,它只把 s 转换成原始的字符串,并返回转换后的值。