DIV CSS 佈局教程網

instanceof 的四個實用場景與程式碼示範
編輯:JavaScript基礎知識     

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

子類實例同時是父類的實例,這是原型鏈查找的直接結果。

例三:字串與日期物件都屬於 Object

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 處理物件。

例四:自訂型別同時屬於 Object

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)。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved