JS类型判断

问题: 对 instanceof 的疑惑

根据MDN关于 instanceof 的描述:
object instanceof constructor
instanceof 运算符用来检测 constructor.prototype 是否存在于参数 object 的原型链上。

关于字面量字符串不能理解为什么不是String的实例。

MDN有这样的例子:

var simpleStr = "This is a simple string"; 
var myString  = new String();
var newStr    = new String("String created with constructor");

simpleStr instanceof String; // returns false, 检查原型链会找到 undefined
myString  instanceof String; // returns true
newStr    instanceof String; // returns true
myString  instanceof Object; // returns true

不太理解这里的检查原型链会找到undefined

我自己测试的时候发现

const s = "abcdefg";

s instanceof String; // false

s.__proto__ === String.prototype; // true

这里字面量字符串的原型链不是有String.prototype吗,那么为什么字面量字符串却不是String的实例?

另外,这是我看到别人写的 instanceof

function instance_of(L, R) {//L 表示左表达式,R 表示右表达式
 var O = R.prototype;// 取 R 的显示原型
 L = L.__proto__;// 取 L 的隐式原型
 while (true) { 
   if (L === null) 
     return false; 
   if (O === L)// 这里重点:当 O 严格等于 L 时,返回 true 
     return true; 
   L = L.__proto__; 
 } 
}

const s = "abc";

instance_of(s, String); // true

这个实现,得到的字面量字符串是String的实例,那么实现上是哪里出了问题?

阅读 2.4k
4 个回答
object instanceof constructor
参数
object
要检测的对象.
constructor
某个构造函数

我猜是右边参数为构造函数,如果给字面字符串,又不是构造函数类型,你左边怎么给,都会为FALSH吧。

判断类型的话toString支持更多选择

(没测试:全凭感觉)
另外在JS中貌似只有对象才存在原型吧,String是一个全局的对象,而你自己创建的字面量是没有原型的。

new String()得到的是一个string对象
clipboard.png

严格判断数据类型的话还是用Object.prototype.toString.call(value)吧

应该是左边的没有被当成对象而当成字符串了,"This is a simple string" instanceof String 这样的话返回值也是false。至于原型链上的确是能找到String.prototype的,所以应该是根本没去链上找。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题