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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM