hasOwnPrototype()
使用hasOwnPrototype()方法可以檢測一個屬性是否存在於實例中,還是存在於原型中。這個方法(不要忘了它是從Object繼承來的)只在給定屬性存在於對象實例中時,才返回true。
看例子:
function Person(){}
Person.prototype.name = "Tom";
Person.prototype.age = 23;
Person.prototype.job = 'Software Engineer';
Person.prototype.sayName = function(){
alert(this.name);
}
var person1 = new Person();
var person2 = new Person();
alert(person1.hasOwnProperty("name")); // false
person1.name = "Jerry";
alert(person1.name); // "Jerry"
alert(person1.hasOwnProperty("name")); // true
alert(person2.name); // "Tom"
alert(person2.hasOwnProperty("name")); // false
delete(person1.name)
alert(person1.name); // "Tom"
alert(person1.hasOwnProperty("name")); // false
可以通過這個判斷,這個屬性是實例的,還是原型的。
當判斷這個實例內有這個屬性時,纔會返回true。
person1.name = "Jerry";
alert(person1.name); // "Jerry"
alert(person1.hasOwnProperty("name")); // true
可以通過代碼看到,實例person1內有屬性 name,這個判斷返回true。
總結:hasOwnProperty()是判斷實例內是否存在這個屬性,如果實例內有這個屬性,返回true,如果沒有這個屬性,返回false。
in
有兩種方法使用in 操作符: 單獨使用和for-in循環使用。在單獨使用時,in操作符會在通過對象能夠訪問能夠訪問給定屬性時返回true,無論屬性是存在實例還是原型中。
可以在上方代碼內添加如下語句測試:
alert("name" in person1);
只要實例或其原型上有這個屬性,返回true。
二者結合的方法
判斷是在實例內還是原型內:
function hasPrototypeProperty(object, num){
return !object.hasOwnProperty(name) && (name in object);
}
由於in操作符只能通過對象能夠訪問到屬性就返回true,hasOwnProperty()只在屬性存在於實例中才返回true,因此只要 in 操作符返回true,而hasOwnProperty()返回false,就可以確定屬性是原型中的屬性。
使用:
alert(hasPrototypeProperty(person1, "name")); // false
如果爲true,說明其存在於原型之中,如果爲false,說明其爲實例屬性。