JavaScript instanceof 的使用方法樣本介紹_基礎知識

來源:互聯網
上載者:User
在 JavaScript 中,判斷一個變數的類型嘗嘗會用 typeof 運算子,在使用 typeof 運算子時採用參考型別儲存值會出現一個問題,無論引用的是什麼類型的對象,它都返回 “object”。這就需要用到instanceof來檢測某個對象是不是另一個對象的執行個體。

通常來講,使用 instanceof 就是判斷一個執行個體是否屬於某種類型。
另外,更重的一點是 instanceof 可以在繼承關係中用來判斷一個執行個體是否屬於它的父類型。
複製代碼 代碼如下:

// 判斷 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

上面的代碼中是判斷了一層繼承關係中的父類,在多層繼承關係中,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,語言規範中是如何定義這個運算子的。2,JavaScript 原型繼承機。大家感興趣的可以去查看相關資料。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.