问题: 对 instanceof 的疑惑根据MDN关于 instanceof 的描述:object instanceof constructorinstanceof 运算符用来检测 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, 检查原型链会找到 undefinedmyString instanceof String; // returns truenewStr instanceof String; // returns truemyString instanceof Object; // returns true不太理解这里的检查原型链会找到undefined我自己测试的时候发现const s = "abcdefg";s instanceof String; // falses.__proto__ === String.prototype; // true这里字面量字符串的原型链不是有String.prototype吗,那么为什么字面量字符串却不是String的实例?另外,这是我看到别人写的 instanceoffunction 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的实例,那么实现上是哪里出了问题?
添加回答
举报
0/150
提交
取消
