You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
functionPerson(){}Person.prototype.name="prototype name";constperson=newPerson();person.age=30;console.log(person.hasOwnProperty("age"));// true,说明 age 属性是对象本身的属性console.log(person.hasOwnProperty("name"));// false,说明 name 属性不在对象本身,而是在原型链上
二、使用 in 操作符结合 hasOwnProperty()
方法介绍:
in操作符用于检查一个对象及其原型链中是否具有指定的属性。
可以结合hasOwnProperty()来判断属性的来源。
示例代码:
functionPerson(){}Person.prototype.name="prototype name";constperson=newPerson();person.age=30;constpropertyName="name";if(person.hasOwnProperty(propertyName)){console.log(`${propertyName} is an own property of the object.`);}elseif(propertyNameinperson){console.log(`${propertyName} is inherited from the prototype.`);}else{console.log(`${propertyName} is not found in the object or its prototype.`);}
functionPerson(){}Person.prototype.name="prototype name";constperson=newPerson();person.age=30;constageDescriptor=Object.getOwnPropertyDescriptor(person,"age");constnameDescriptor=Object.getOwnPropertyDescriptor(person,"name");if(ageDescriptor){console.log("age is an own property of the object.");}if(!nameDescriptor){console.log("name is not an own property of the object.");}
The text was updated successfully, but these errors were encountered:
关键词:对象与原型链
在 JavaScript 中,可以通过以下几种方式来判断一个属性是来自对象本身还是来自原型链:
一、使用
hasOwnProperty()
方法方法介绍:
hasOwnProperty()
是 JavaScript 对象的一个方法,用于判断一个对象自身是否具有指定的属性。示例代码:
二、使用
in
操作符结合hasOwnProperty()
方法介绍:
in
操作符用于检查一个对象及其原型链中是否具有指定的属性。hasOwnProperty()
来判断属性的来源。示例代码:
三、使用
Object.getOwnPropertyDescriptor()
方法方法介绍:
Object.getOwnPropertyDescriptor()
方法返回指定对象上一个自有属性的属性描述符。undefined
。示例代码:
The text was updated successfully, but these errors were encountered: