|
在《Javascript類型檢測(cè)》一文中講到了用instanceof來(lái)用做檢測(cè)類型,讓我們來(lái)回顧一下:
那么instanceof的這種行為到底是如何實(shí)現(xiàn)的呢,現(xiàn)在讓我們揭開instanceof背后的迷霧。
instanceof原理
照慣例,我們先來(lái)看一段代碼:
function Cat(){}Cat.prototype = {}function Dog(){}Dog.prototype ={}var dog1 = new Dog();alert(dog1 instanceof Dog);//truealert(dog1 instanceof Object);//trueDog.prototype = Cat.prototype;alert(dog1 instanceof Dog);//falsealert(dog1 instanceof Cat);//falsealert(dog1 instanceof Object);//true;var dog2= new Dog();alert(dog2 instanceof Dog);//truealert(dog2 instanceof Cat);//truealert(dog2 instanceof Object);//trueDog.prototype = null;var dog3 = new Dog();alert(dog3 instanceof Cat);//falsealert(dog3 instanceof Object);//truealert(dog3 instanceof Dog);//error
it知識(shí)庫(kù):理解Javascript_07_理解instanceof實(shí)現(xiàn)原理,轉(zhuǎn)載需保留來(lái)源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。