JavaScript instanceof 的使用方法有哪些

時間:2024-10-18 18:33:17 JavaScript 我要投稿
  • 相關(guān)推薦

JavaScript instanceof 的使用方法有哪些

  在 JavaScript 中,判斷一個變量的類型嘗嘗會用 typeof 運算符,在使用 typeof 運算符時采用引用類型存儲值會出現(xiàn)一個問題,無論引用的是什么類型的對象,它都返回 “object”。這就需要用到instanceof來檢測某個對象是不是另一個對象的實例。

  通常來講,使用 instanceof 就是判斷一個實例是否屬于某種類型。

  另外,更重的一點是 instanceof 可以在繼承關(guān)系中用來判斷一個實例是否屬于它的父類型。

  復制代碼 代碼如下:

  // 判斷 foo 是否是 Foo 類的實例 , 并且是否是其父類型的實例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 運算符同樣適用。

  instanceof 復雜用法

  復制代碼 代碼如下:

  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 的奧秘,需要從兩個方面著手:1,語言規(guī)范中是如何定義這個運算符的。2,JavaScript 原型繼承機。大家感興趣的可以去查看相關(guān)資料。

【JavaScript instanceof 的使用方法有哪些】相關(guān)文章:

詳解JavaScript中的splice()使用方法08-20

Javascript中arguments對象的詳解和使用方法08-20

健身器材使用方法有哪些10-04

java中File類有哪些使用方法06-30

關(guān)于javascript對象之內(nèi)置和對象Math的使用方法10-08

對javascript的理解08-08

常用的JavaScript模式09-22

Javascript的this用法簡述08-15

JavaScript學習筆記08-24

JavaScript 基礎(chǔ)教學09-29

亚洲制服丝袜二区欧美精品,亚洲精品无码视频乱码,日韩av无码一区二区,国产人妖视频一区二区
永久免费A在线观看全网站 亚洲日韩AV在线不卡 | 中文字幕欧美精品制服丝袜 | 亚洲一级在线中文字幕 | 亚洲欧美国产另类 | 亚洲欧美精品综合欧美一区 | 亚洲欧洲日本免费看 |