JavaScript中instanceof運(yùn)算符的使用示例
instanceof運(yùn)算符可以用來判斷某個(gè)構(gòu)造函數(shù)的prototype屬性是否存在另外一個(gè)要檢測對象的原型鏈上。
實(shí)例一:普遍用法
A instanceof B :檢測B.prototype是否存在于參數(shù)A的原型鏈上.
function Ben() {
}
var ben = new Ben();
console.log(ben instanceof Ben);//true
實(shí)例二:繼承中判斷實(shí)例是否屬于它的父類
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
實(shí)例三:表明String對象和Date對象都屬于Object類型
下面的代碼使用了instanceof來證明:String和Date對象同時(shí)也屬于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; // returns false, 檢查原型鏈會(huì)找到 undefined
myString instanceof String; // returns true
newStr instanceof String; // returns true
myString instanceof Object; // returns true
myObj instanceof Object; // returns true, despite an undefined prototype
({}) instanceof Object; // returns true, 同上
myString instanceof Date; // returns false
myDate instanceof Date; // returns true
myDate instanceof Object; // returns true
myDate instanceof String; // returns false
實(shí)例四:演示mycar屬于Car類型的同時(shí)又屬于Object類型
下面的代碼創(chuàng)建了一個(gè)類型Car,以及該類型的對象實(shí)例mycar. instanceof運(yùn)算符表明了這個(gè)mycar對象既屬于Car類型,又屬于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
- JavaScript中isPrototypeOf函數(shù)
- JS中的hasOwnProperty()和isPrototypeOf()屬性實(shí)例詳解
- JavaScript中isPrototypeOf函數(shù)作用和使用實(shí)例
- js中的hasOwnProperty和isPrototypeOf方法使用實(shí)例
- JavaScript isPrototypeOf和hasOwnProperty使用區(qū)別
- java 中的instanceof用法詳解及instanceof是什么意思(推薦)
- Javascript typeof與instanceof的區(qū)別
- JavaScript的instanceof運(yùn)算符學(xué)習(xí)教程
- JavaScript中instanceof運(yùn)算符的用法總結(jié)
- JavaScript instanceof 的使用方法示例介紹
- JavaScript中isPrototypeOf、instanceof和hasOwnProperty函數(shù)的用法詳解
相關(guān)文章
Javascript中eval函數(shù)的使用方法與示例
JavaScript有許多小竅門來使編程更加容易。其中之一就是eval()函數(shù),這個(gè)函數(shù)可以把一個(gè)字符串當(dāng)作一個(gè)JavaScript表達(dá)式一樣去執(zhí)行它。以下是它的說明2007-04-04
淺談js和css內(nèi)聯(lián)外聯(lián)注意事項(xiàng)
下面小編就為大家?guī)硪黄獪\談js和css內(nèi)聯(lián)外聯(lián)注意事項(xiàng)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-06-06
使用Java實(shí)現(xiàn)簡單的server/client回顯功能的方法介紹
本篇文章介紹了,使用Java實(shí)現(xiàn)簡單的server/client回顯功能的方法。需要的朋友參考下2013-05-05
客戶端腳本中常常出現(xiàn)的一些問題和調(diào)試技巧
客戶端腳本中常常出現(xiàn)的一些問題和調(diào)試技巧...2007-01-01
JavaScript中的setUTCDate()方法使用詳解
這篇文章主要介紹了JavaScript中的setUTCDate()方法使用詳解,是JS入門學(xué)習(xí)中的基礎(chǔ)知識(shí),需要的朋友可以參考下2015-06-06

