instanceof 的作用是判斷某個建構函式的 prototype 屬性,是否存在於另一個待檢測物件的原型鏈上。以下用四個由淺入深的例子把它的行為看完整。
A instanceof B,問的是「B.prototype 在不在 A 的原型鏈上」。
function Ben() {}
var ben = new Ben();
console.log(ben instanceof Ben); // true
function Ben_parent() {}
function Ben_son() {}
Ben_son.prototype = new Ben_parent(); // 原型繼承
var ben_son = new Ben_son();
console.log(ben_son instanceof Ben_son); // true
console.log(ben_son instanceof Ben_parent); // true
子類實例同時是父類的實例,這是原型鏈查找的直接結果。
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; // false,原始值沒有原型鏈,查到 undefined
myString instanceof String; // true
newStr instanceof String; // true
myString instanceof Object; // true
myObj instanceof Object; // true
({}) instanceof Object; // true,同上
myString instanceof Date; // false
myDate instanceof Date; // true
myDate instanceof Object; // true
myDate instanceof String; // false
這組對照很值得記住:用字面值宣告的字串是原始值,instanceof 判斷為 false;只有用 new String() 產生的包裝物件才會是 true。這也是為什麼型別判斷通常建議用 typeof 處理原始值、用 instanceof 處理物件。
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
var mycar = new Car("Honda", "Accord", 1998);
var a = mycar instanceof Car; // true
var b = mycar instanceof Object; // true
因為所有自訂型別的 prototype 最終都鏈到 Object.prototype,所以任何物件對 Object 做 instanceof 都會得到 true——除非你把原型鏈中斷(例如將 prototype 設為 null)。