JavaScript如何判断对象中的属性存在自身还是原型链上

1.in操作符

in 操作符会在通过对象能够访问给定属性时返回true,无论该属性存在于对象本身还是其原型链上。

javascript 复制代码
function Person(name) {
  this.name = name
}
let obj = new Person('Tom')

Person.prototype.gender = 'male'
Person.prototype.code = 23
console.log("name" in obj) // true
console.log('code' in obj) // true
console.log('gender' in obj) // true

2.obj.hasOwnProperty(prop)

hasOwnProperty() 方法会返回一个布尔值,指示对象自身属性中是否具有指定的属性。

对象本身有,返回true;反之,返回false。

javascript 复制代码
function Person(name) {
  this.name = name
}
let obj = new Person('Tom')

Person.prototype.gender = 'male'
Person.prototype.code = 23

console.log(obj.hasOwnProperty('name')) // true
console.log(obj.hasOwnProperty('code')) // false
console.log(obj.hasOwnProperty('gender')) // false

3.两者结合判断属性位于对象本身还是来自于其原型链

javascript 复制代码
function Person(name) {
  this.name = name
}
let obj = new Person('Tom')

Person.prototype.gender = 'male'
Person.prototype.code = 23

function propertyFormPrototype(obj, prop) {
  return obj.hasOwnProperty(prop) && prop in obj
  //当return为true时表示属性位于对象本身
}
console.log(propertyFormPrototype(obj, 'name')) // true
console.log(propertyFormPrototype(obj, 'gender')) // false
console.log(propertyFormPrototype(obj, 'code')) // false
相关推荐
2301_792308251 分钟前
C++与自动驾驶系统
开发语言·c++·算法
hongtianzai4 分钟前
Laravel8.x核心特性全解析
java·c语言·开发语言·golang·php
2401_874732537 分钟前
模板编译期排序算法
开发语言·c++·算法
weixin_421922698 分钟前
C++与Node.js集成
开发语言·c++·算法
chushiyunen11 分钟前
python cosyVoice实现tts文本转语音、音频(未完成)
开发语言·python·音视频
hongtianzai12 分钟前
Laravel6.x重磅发布:LTS版本新特性全解析
c语言·开发语言·php·laravel
optimistic_chen14 分钟前
【Vue3入门】Pinia 状态管理 和 ElementPlus组件库
前端·javascript·vue.js·elementui·pinia·组件
kgduu15 分钟前
js之网络请求与远程资源
开发语言·javascript·网络
酉鬼女又兒17 分钟前
零基础入门前端JavaScript 核心语法:var/let/const、箭头函数与 setTimeout 循环陷阱全解析(可用于备赛蓝桥杯Web应用开发)
开发语言·前端·javascript·蓝桥杯
暮冬-  Gentle°17 分钟前
设计模式在C++中的实现
开发语言·c++·算法