constructor
原型对象prototype有一个constructor属性,默认指向原型对象prototype所在的构造函数
function F() {}
F.prototype.constructor === F // truefunction P() {}
var p = new P()
p.constructor === P // true
p.constructor === P.prototype.constructor // true
p.hasOwnProperty('constructor') // false //p自身没有constructor属性,该属性是从原型链上读取instanceof
instanceof返回一个布尔值,表示对象是否为某个构造函数的实例。instanceof的左边是实例对象,右边是构造函数,它会检查右边构造函数是否在左边实例对象的原型链上
function V() {}
var v = new V()
v instanceof V // trueinstanceof会检查整个原型链,所以同一个实例对象,对多个构造函数都返回true
var d= new Date()
d instanceof Date // true
d instanceof Object // true当左边对象的原型链上只有null时,instanceof的判断会失真
var obj = Object.create(null)
typeof obj // object
Object.create(null) instanceof Object // false注意,instanceof运算符只能用于对象,不适用原始类型的值
var str = 'abc'
str instanceof String // false对于undefined和null,instanceof总会返回false
null instanceof Object // false
undefined instanceof Object // false应用:利用instanceof可以解决调用构造函数时忘记加new命令的问题
function Person(name) {
if (this instanceof Person) { this.name = name
} else {
return new Person(name)
}
}