国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > JavaScript > 正文

JavaScript instanceof 的使用方法示例介紹

2019-11-20 21:51:31
字體:
供稿:網(wǎng)友
在 JavaScript 中,判斷一個(gè)變量的類型嘗嘗會(huì)用 typeof 運(yùn)算符,在使用 typeof 運(yùn)算符時(shí)采用引用類型存儲(chǔ)值會(huì)出現(xiàn)一個(gè)問題,無論引用的是什么類型的對(duì)象,它都返回 “object”。這就需要用到instanceof來檢測(cè)某個(gè)對(duì)象是不是另一個(gè)對(duì)象的實(shí)例。

通常來講,使用 instanceof 就是判斷一個(gè)實(shí)例是否屬于某種類型。
另外,更重的一點(diǎn)是 instanceof 可以在繼承關(guān)系中用來判斷一個(gè)實(shí)例是否屬于它的父類型。
復(fù)制代碼 代碼如下:

// 判斷 foo 是否是 Foo 類的實(shí)例 , 并且是否是其父類型的實(shí)例function Aoo(){}
function Foo(){}
Foo.prototype = new Aoo();//JavaScript 原型繼承
var foo = new Foo();
console.log(foo instanceof Foo)//true
console.log(foo instanceof Aoo)//true

上面的代碼中是判斷了一層繼承關(guān)系中的父類,在多層繼承關(guān)系中,instanceof 運(yùn)算符同樣適用。

instanceof 復(fù)雜用法
復(fù)制代碼 代碼如下:

function Cat(){}
Cat.prototype = {}

function Dog(){}
Dog.prototype ={}

var dog1 = new Dog();
alert(dog1 instanceof Dog);//true
alert(dog1 instanceof Object);//true

Dog.prototype = Cat.prototype;
alert(dog1 instanceof Dog);//false
alert(dog1 instanceof Cat);//false
alert(dog1 instanceof Object);//true;

var dog2= new Dog();
alert(dog2 instanceof Dog);//true
alert(dog2 instanceof Cat);//true
alert(dog2 instanceof Object);//true

Dog.prototype = null;
var dog3 = new Dog();
alert(dog3 instanceof Cat);//false
alert(dog3 instanceof Object);//true
alert(dog3 instanceof Dog);//error

要想從根本上了解 instanceof 的奧秘,需要從兩個(gè)方面著手:1,語言規(guī)范中是如何定義這個(gè)運(yùn)算符的。2,JavaScript 原型繼承機(jī)。大家感興趣的可以去查看相關(guān)資料。
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 新竹市| 图们市| 临汾市| 安远县| 拉萨市| 鄱阳县| 荃湾区| 刚察县| 东乡县| 望谟县| 巫溪县| 沙洋县| 吉木乃县| 磐石市| 闽清县| 尼木县| 金华市| 深泽县| 株洲县| 互助| 宜丰县| 武山县| 扶余县| 大足县| 泽库县| 陵水| 龙胜| 思茅市| 锦屏县| 工布江达县| 汪清县| 塘沽区| 康定县| 河南省| 阿鲁科尔沁旗| 珲春市| 潜江市| 孝昌县| 慈利县| 威海市| 广宁县|