JavaScript类型检测笔记之constructor

Js
yutao

constructor

语法:object.constructor
作用:返回创建了当前这个对象实例的构造函数
描述:新函数创建时,该函数的原型对象下都会获得一个constructor属性
检测一下:

1
2
3
4
5
6
7
8
9
10
11
12
13
var str = new String('123'),
		str2 = '2121',
		date = new Date(),
		Fn = function(){},
		fn1 = new Fn(),
		obj = {};
console.log(str.constructor === String);//true
console.log(str2.constructor === String);//true
console.log(date.constructor === Date);//true
console.log(Fn.constructor === Function);//true
console.log(fn1.constructor === Fn);//true
console.log(Fn.prototype.constructor === Fn);//true
console.log(obj.constructor === Object);//true

按照上面的例子来看,好像解决了typeof不能解决的问题,但这个事例开头的描述里已经说明:“函数的原型对象下都会获得一个constructor属性”,这句话暴露了constructor判断类型的一个弱点,constructor是原型对象的一个属性,问题出来了,我们在用构造原型模式或者做一些继承的时候,原型(prototype)这家伙经常被我们放置实例共享的一些属性和方法。改写后的prototype的constructor属性会不会有影响?看下代码。

1
2
3
4
5
6
7
8
9
10
function D(){};
var newd = new D();
console.log(D.prototype.constructor === D);//true
console.log(newd.constructor === D);//true

D.prototype = {};// 等价于 D.prototype = new Object();
var newdd = new D();
console.log(D.prototype.constructor === D);//false
console.log(D.prototype.constructor === Object);//true
console.log(newdd.constructor === Object);//true

constructor也是不靠谱的,并且此属性最初是用来标识对象类型的,用来检测类型总觉得有些别扭
相关:
JavaScript类型检测笔记之typeof
JavaScript类型检测笔记之instanceof