問題: 對 instanceof 的疑惑根據(jù)MDN關(guān)于 instanceof 的描述:object instanceof constructorinstanceof 運算符用來檢測 constructor.prototype 是否存在于參數(shù) object 的原型鏈上。關(guān)于字面量字符串不能理解為什么不是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我自己測試的時候發(fā)現(xiàn)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這個實現(xiàn),得到的字面量字符串是String的實例,那么實現(xiàn)上是哪里出了問題?
JS類型判斷
慕田峪4524236
2019-03-07 18:19:10