1. 程式人生 > 實用技巧 >js-object-屬性判斷

js-object-屬性判斷

isPrototypeOf

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)

instanceof

instanceof操作符用於判斷:某個物件是否存在另外一個要檢測物件的原型鏈上。

A instanceof B內部判斷邏輯是:沿著A的原型鏈一直往上找,如果發現A的隱式原型和B的原型相同,那麼就返回true

function myInstanceof(A, B) {
	while(A.__proto__ != null) {
		if(A.__proto__ === B.prototype) return true;
		A = A.__proto__;
	}
	return false;
}
myInstanceof(/1/g, RegExp); // true
myInstanceof(/1/g, Object); // true
myInstanceof(new Date(), Date); // true