JavaScript中的比較

JS中的比較

==與===

'1' == 1;
true == 1;
false == 0;
"\n \n \t" == 0;

==會進行類型轉(zhuǎn)換,所以結(jié)果為true

'1' === 1;
true === 1;
false === 0;
"\n \n \t" === 0;

===會判斷內(nèi)容和類型是否匹配,所以結(jié)果為false。建議都使用===,因為==的轉(zhuǎn)換并不好記憶,===可以幫助我們確保結(jié)果是我們所期望的。

instanceof

有的時候我們需要判斷\n

  1. 一個object是否由某個構(gòu)造函數(shù)創(chuàng)建的(是否是某類型)
  2. 一個object是否有某個原型(繼承了某些方法)
    這個需求可以用instanceof來完成

語法

object instanceof constructor

參數(shù)

要檢測的對象.

object

某個構(gòu)造函數(shù)

constructor

描述

instanceof 運算符用來檢測 constructor.prototype 是否存在于參數(shù) object 的原型鏈上。

舉個例子

看一下這段代碼,定義了一個People基類,然后

  1. 定義Man類的原型是People.prototype。
  2. 定義Woman類繼承People。
    這然對象man和woman都可以訪問eat方法,woman還可以訪問name屬性
function People(name){
    this.name = name;
}
People.prototype={
    eat:function(){
        console.log(this.name+"要吃飯");
    }
};
function Man(tall, rich, handsome){
    this.tall = tall;
    this.rich = rich;
    this.handsome = handsome;
}
function Woman(white, rich, pretty){
    this.white=white;
    this.rich=rich;
    this.pretty=pretty;
}
//Object.create() 方法創(chuàng)建一個擁有指定原型和若干個指定屬性的對象。
Man.prototype=Object.create(People.prototype); //只是可以訪問eat方法
Woman.prototype= new People("Alice");   //繼承
var man = new Man("不高","不富","不帥");
var woman = new Woman("不白","不富","不美");
man.eat();//-->undefined要吃飯
woman.eat();//-->Alice要吃飯

如果我們要檢查一下對象是否有eat方法,那么就可以使用instanceof方法了,看一下下面代碼

//-->true;因為Object.getPrototypeOf(man) === Man.prototype符合定義
console.log(man instanceof Man);
//-->true;People.prototype.isPrototypeOf(man)
console.log(man instanceof People);
//-->true;Object.prototype.isPrototypeOf(man)
console.log(man instanceof Object);

//-->true;因為Object.getPrototypeOf(woman) === Woman.prototype符合定義
console.log(woman instanceof Woman);
//-->true;People.prototype.isPrototypeOf(woman)
console.log(woman instanceof People);
//-->true;Object.prototype.isPrototypeOf(woman)
console.log(woman instanceof Object);

function PlaseEat(p){
    if(p instanceof People){
        p.eat();
    }else{
        console.log("沒有繼承People,所以不能屌用eat方法");
    }
}

可以注意到:

  1. man instanceof Man返回true,這是因為man的原型是Man.prototype,就是原型鏈的開始,符合instanceof的功能定義。
  2. man instanceof People返回true,是因為Man.prototypePeople的原型是同一個對象。Object.create() 方法創(chuàng)建一個擁有指定原型和若干個指定屬性的對象。
  3. man instanceof Object返回true,是因為Object.prototype.isPrototypeOf(man)
  4. PlaseEat函數(shù)利用instanceof判斷出對象是否有People中定義的接口,如果有,就可以調(diào)用eat方法了。

有一個地方比較奇怪,大家看看這個

var simpleStr = "This is a simple string"; 
simpleStr instanceof String;

居然返回false。JS的行為有時候還真奇怪。var newStr = new String("String created with constructor");這樣定義就可以返回true。感覺JS的語言細節(jié)方面不是特別的講究啊。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容