JS中的比較
==與===
'1' == 1;
true == 1;
false == 0;
"\n \n \t" == 0;
==會進行類型轉換,所以結果為true
'1' === 1;
true === 1;
false === 0;
"\n \n \t" === 0;
===
會判斷內容和類型是否匹配,所以結果為false
。建議都使用===
,因為==
的轉換并不好記憶,===
可以幫助我們確保結果是我們所期望的。
instanceof
有的時候我們需要判斷\n
- 一個object是否由某個構造函數創建的(是否是某類型)
- 一個object是否有某個原型(繼承了某些方法)
這個需求可以用instanceof
來完成
語法
object instanceof constructor
參數
要檢測的對象.
object
某個構造函數
constructor
描述
instanceof 運算符用來檢測 constructor.prototype 是否存在于參數 object 的原型鏈上。
舉個例子
看一下這段代碼,定義了一個People基類,然后
- 定義Man類的原型是People.prototype。
- 定義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() 方法創建一個擁有指定原型和若干個指定屬性的對象。
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方法");
}
}
可以注意到:
-
man instanceof Man
返回true
,這是因為man
的原型是Man.prototype
,就是原型鏈的開始,符合instanceof
的功能定義。 -
man instanceof People
返回true
,是因為Man.prototype
和People
的原型是同一個對象。Object.create()
方法創建一個擁有指定原型和若干個指定屬性的對象。 -
man instanceof Object
返回true
,是因為Object.prototype.isPrototypeOf(man)
-
PlaseEat
函數利用instanceof判斷出對象是否有People中定義的接口,如果有,就可以調用eat
方法了。
有一個地方比較奇怪,大家看看這個
var simpleStr = "This is a simple string";
simpleStr instanceof String;
居然返回false。JS的行為有時候還真奇怪。var newStr = new String("String created with constructor");
這樣定義就可以返回true
。感覺JS的語言細節方面不是特別的講究啊。