问题: 对 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的实例,那么实现上是哪里出了问题?
我猜是右边参数为构造函数,如果给字面字符串,又不是构造函数类型,你左边怎么给,都会为FALSH吧。