如何判斷一個對象的方法是來自這個自己的仍是原型的?this
function Person() { } Person.prototype.name="Nicholas"; Person.prototype.age=29; Person.prototype.sayName=function(){ alert(this.name); } var person1=new Person(); person1.name="Greg"; var person2=new Person(); console.log(person1.hasOwnProperty("name"));//true console.log(person2.hasOwnProperty("name"));//false console.log("name" in person1);//true console.log("name" in person2);//true for (var prop in person1) { console.log(prop);//name age sayName } function hasPrototypeProperty(object,pro) {//如此可判斷存在於原型中的屬性 return (!object.hasOwnProperty(pro))&&(pro in object); } console.log(hasPrototypeProperty(person1,"name"));//false console.log(hasPrototypeProperty(person2,"name"));//true
function
Person() {
}
Person.prototype.name=
"Nicholas"
;
Person.prototype.age=29;
Person.prototype.sayName=
function
(){
alert(
this
.name);
}
var
person1=
new
Person();
person1.name=
"Greg"
;
var
person2=
new
Person();
console.log(person1.hasOwnProperty(
"name"
));
//true
console.log(person2.hasOwnProperty(
"name"
));
//false
console.log(
"name"
in
person1);
//true
console.log(
"name"
in
person2);
//true
for
(
var
prop
in
person1) {
console.log(prop);
//name age sayName
}
function
hasPrototypeProperty(object,pro) {
//如此可判斷存在於原型中的屬性
return
(!object.hasOwnProperty(pro))&&(pro
in
object);
}
console.log(hasPrototypeProperty(person1,
"name"
));
//false
console.log(hasPrototypeProperty(person2,
"name"
));
//true
|