JS里面判斷數(shù)據(jù)類型,一般用typeof或者instanceof兩種方法淹冰,那么购啄,兩者到底有什么區(qū)別呢睁宰?
1. typeof
typeof用于基本數(shù)據(jù)類型的類型判斷,返回值都為小寫的字符串寝凌。如果是對(duì)象柒傻,除了function類型會(huì)返回“function”, 其他對(duì)象統(tǒng)一返回“object”。詳情如下:
小貼士:
JavaScript基本數(shù)據(jù)類型為:
null, undefined, number, string, boolean, object
2. instanceof
instanceof 利用原型鏈繼承關(guān)系做判斷较木,它針對(duì)對(duì)象類型(格式:對(duì)象 instanceof 構(gòu)造函數(shù)
)诅愚。
“盡管instanceof 運(yùn)算符的右操作數(shù)是構(gòu)造函數(shù),但計(jì)算過程實(shí)際上是檢測(cè)了對(duì)象的繼承關(guān)系劫映,而不是檢測(cè)創(chuàng)建對(duì)象的構(gòu)造函數(shù) ”(摘自《JavaScript權(quán)威指南》)
2.1 原型對(duì)象
一旦創(chuàng)建一個(gè)新函數(shù)违孝,就會(huì)根據(jù)一組特定的規(guī)則為該函數(shù)創(chuàng)建一個(gè)prototype
屬性,該屬性指向函數(shù)的原型對(duì)象XXX.prototype
泳赋。在默認(rèn)情況下雌桑,所有原型對(duì)象會(huì)自動(dòng)獲得一個(gè)constructor
屬性,該屬性指向這個(gè)函數(shù)祖今。
MDN上對(duì)原型上constructor
的解釋如下:
Returns a reference to the Object constructor function that created the instance object.
Note that the value of this property is a reference to the function itself, not a string containing the function's name.
譯文:返回一個(gè)指向創(chuàng)建了該對(duì)象原型的函數(shù)引用校坑。
需要注意的是,該屬性的值是那個(gè)函數(shù)本身千诬,而不是一個(gè)包含函數(shù)名稱的字符串耍目。
所有的對(duì)象都有constructor屬性。如果一個(gè)對(duì)象沒有顯性指定constructor值徐绑,那么它將指向原始構(gòu)造函數(shù)邪驮。如下所示:
var o = new Object;
o.constructor === Object; //true
var a = [];
a.constructor === Array; // true
var a = new Array;
a.constructor === Array //true
var n = new Number(3);
n.constructor === Number; // true
2.2 原型鏈繼承
下面是一個(gè)典型原型鏈繼承:
function SuperType() {
this.property = true;
}
SuperType.prototype.getSuperValue = function () {
return this.property;
};
function SubType() {
this.subproperty = false;
}
SubType.prototype = new SuperType();
SubType.prototype.getSubValue = function () {
return this.subproperty;
};
var instance = new SubType();
參考下圖,可以看到傲茄,實(shí)例instance是由構(gòu)造函數(shù)SubType創(chuàng)建的毅访,默認(rèn)情況下,instance的__proto__
屬性指向SubType.prototype
(instance.constructor === SubType)盘榨。但是喻粹,由于做了SubType.prototype = new SuperType()
操作,導(dǎo)致SubType.prototype
指針指向SuperType的一個(gè)實(shí)例草巡,并且SuperType實(shí)例的__proto__
屬性指向SuperType.prototype
守呜。
由此,生成原型鏈山憨。
這時(shí)根據(jù)用instanceof
做類型檢測(cè)查乒,結(jié)果如下:
instance instanceof SubType === true
instance instanceof SuperType === true
小貼士
如果把上面原型鏈繼承的例子稍微做個(gè)改動(dòng),調(diào)整兩行代碼的順序萍歉,如下:
SubType.prototype.getSubValue = function () {
return this.subproperty;
};
SubType.prototype = new SuperType();
var instance = new SubType();
console.log(instance.getSubValue) // undefined
答案是undefined侣颂!原因是,SubType.prototype指針指向新的對(duì)象枪孩,導(dǎo)致無法訪問之前老對(duì)象上的方法。
小結(jié)
- typeof用于基本數(shù)據(jù)類型的類型判斷,無法甄別對(duì)象具體類型(除了function);
- instanceof用于對(duì)象的類型判斷蔑舞,基于原型鏈上的繼承關(guān)系;
(感謝@文興的發(fā)現(xiàn)拒担,文章于2017-3-6日被更正)