instanceof 運(yùn)算符用來測(cè)試一個(gè)對(duì)象在其原型鏈中是否存在一個(gè)構(gòu)造函數(shù)的 prototype 屬性。
引自 MDN
但是MDN中如下代碼:
var simpleStr = "This is a simple string";
var myString = new String();
var newStr = new String("String created with constructor");
var myDate = new Date();
var myObj = {};
simpleStr instanceof String; // returns false, 檢查原型鏈會(huì)找到 undefined
我經(jīng)過測(cè)試發(fā)現(xiàn):
simpleStr.__proto__ === String.prototype // true
Object.getPrototypeOf(simpleStr) === String.prototype //true
String.prototype明明就在simpleStr的原型鏈上啊, 但是 simpleStr instanceof String; 返回了false...
js真坑, 唯一一種解釋就是,字面量是沒有原型的。 但是為何此處Object.getPrototypeOf(simpleStr) 能獲得原型。。