JavaScript的hasOwnProperty和isPrototypeOf详解
本文由 小茗同学 发表于 2016-08-22 浏览(4173)
最后修改 2018-05-14 标签:javascript hasownproperty isprototypeof prototype

作用

hasOwnProperty的作用是用来判断一个对象本身是否具有某个属性或对象,对象本身的意思是指不包括它的原型链,个人觉得这个方法应该叫isOwnProperty更合适。

isPrototypeOf是用来判断对象是否存在于另一个对象的原型链中,如:

Array.prototype.isPrototypeOf([1, 2, 3]);

几个例子

下面几个例子应该很好理解:

String.prototype.hasOwnProperty('split'); // 输出 true
'http://liuxianan.com'.hasOwnProperty('split'); // 输出 false
({testFn:function(){}}).hasOwnProperty('testFn'); // 输出 true

更复杂一点的例子

function People(name)
{
	this.name = name;
	this.showName = function()
	{
		console.log('showName:'+this.name);
	};
}
People.prototype.setGender = function(gender)
{
	this.gender = gender;
	console.log('setGender:'+this.gender);
};
var lxa = new People('小茗同学');
lxa.age = 24;
lxa.setGender('man');
console.log(lxa.hasOwnProperty('name')); // true
console.log(lxa.hasOwnProperty('age')); // true
console.log(lxa.hasOwnProperty('showName')); // true
console.log(lxa.hasOwnProperty('gender')); // true
console.log(lxa.hasOwnProperty('setGender')); // false
console.log(People.prototype.hasOwnProperty('setGender')); // true
console.log(People.prototype.hasOwnProperty('gender')); // false
console.log(People.prototype.isPrototypeOf(lxa)); // true
//isPrototypeOf错误写法:lxa.isPrototypeOf(People)