要判断javascript对象的属性是否来自原型链,最稳妥的方法是结合in操作符和object.prototype.hasownproperty.call()。1. 使用prop in obj检查属性是否存在于对象或其原型链上;2. 使用object.prototype.hasownproperty.call(obj, prop)判断属性是否为对象自身属性;3. 若前者为true且后者为false,则该属性来自原型链。此方法可准确区分实例属性与原型属性,避免因对象重写hasownproperty导致的判断错误,确保属性来源判断的可靠性,适用于深拷贝、序列化等需精确控制属性的场景。

要判断一个JavaScript对象的属性究竟是它自己的(实例属性)还是从原型链上继承来的,最常用也最稳妥的方法就是结合
in
Object.prototype.hasOwnProperty.call()
prop in obj
obj.hasOwnProperty(prop)

判断属性是否在原型上,核心思路就是利用
in
hasOwnProperty
in
hasOwnProperty
所以,一个属性如果满足以下两个条件,就可以确定它来自原型:

propertyName in object
true
object.hasOwnProperty(propertyName)
false
结合起来就是:
!(obj.hasOwnProperty(prop)) && (prop in obj)
看个例子:

function Person(name) {
this.name = name; // 实例属性
}
Person.prototype.greet = function() { // 原型属性
console.log(`Hello, my name is ${this.name}`);
};
const person1 = new Person('Alice');
person1.age = 30; // 实例属性
// 检查 'name' 属性
console.log('--- 检查 name (实例属性) ---');
console.log(`'name' in person1: ${'name' in person1}`); // true
console.log(`person1.hasOwnProperty('name'): ${person1.hasOwnProperty('name')}`); // true
console.log(`'name' 在原型上吗? ${!person1.hasOwnProperty('name') && ('name' in person1)}`); // false
// 检查 'greet' 属性
console.log('\n--- 检查 greet (原型属性) ---');
console.log(`'greet' in person1: ${'greet' in person1}`); // true
console.log(`person1.hasOwnProperty('greet'): ${person1.hasOwnProperty('greet')}`); // false
console.log(`'greet' 在原型上吗? ${!person1.hasOwnProperty('greet') && ('greet' in person1)}`); // true
// 检查 'toString' 属性 (更深的原型链,来自 Object.prototype)
console.log('\n--- 检查 toString (更深的原型属性) ---');
console.log(`'toString' in person1: ${'toString' in person1}`); // true
console.log(`person1.hasOwnProperty('toString'): ${person1.hasOwnProperty('toString')}`); // false
console.log(`'toString' 在原型上吗? ${!person1.hasOwnProperty('toString') && ('toString' in person1)}`); // true
// 检查 'age' 属性 (实例属性)
console.log('\n--- 检查 age (实例属性) ---');
console.log(`'age' in person1: ${'age' in person1}`); // true
console.log(`person1.hasOwnProperty('age'): ${person1.hasOwnProperty('age')}`); // true
console.log(`'age' 在原型上吗? ${!person1.hasOwnProperty('age') && ('age' in person1)}`); // false
// 检查一个不存在的属性
console.log('\n--- 检查 nonexistent (不存在的属性) ---');
console.log(`'nonexistent' in person1: ${'nonexistent' in person1}`); // false
console.log(`person1.hasOwnProperty('nonexistent'): ${person1.hasOwnProperty('nonexistent')}`); // false
console.log(`'nonexistent' 在原型上吗? ${!person1.hasOwnProperty('nonexistent') && ('nonexistent' in person1)}`); // false这里值得一提的是,
hasOwnProperty
Object.prototype.hasOwnProperty.call(obj, prop)
const objWithOverriddenHasOwnProperty = {
myProp: 1,
hasOwnProperty: function() {
return false; // 故意返回 false
}
};
console.log('\n--- 使用 Object.prototype.hasOwnProperty.call() ---');
console.log(`objWithOverriddenHasOwnProperty.hasOwnProperty('myProp'): ${objWithOverriddenHasOwnProperty.hasOwnProperty('myProp')}`); // false (被覆盖了)
console.log(`Object.prototype.hasOwnProperty.call(objWithOverriddenHasOwnProperty, 'myProp'): ${Object.prototype.hasOwnProperty.call(objWithOverriddenHasOwnProperty, 'myProp')}`); // true (正确判断)
// 所以判断原型属性,更严谨的写法是:
const isPrototypeProperty = (obj, prop) => !Object.prototype.hasOwnProperty.call(obj, prop) && (prop in obj);
console.log(`'myProp' 在 objWithOverriddenHasOwnProperty 的原型上吗? ${isPrototypeProperty(objWithOverriddenHasOwnProperty, 'myProp')}`); // false (因为它是实例属性)这样处理,哪怕遇到一些“奇奇怪怪”的对象,比如它们自己重写了
hasOwnProperty
in
说实话,刚接触JavaScript的时候,我个人也曾被
in
in
举个例子,
Object.prototype
toString
valueOf
{}'toString' in {}true
Object.prototype.toString
const myObj = {};
console.log(`'toString' in myObj: ${'toString' in myObj}`); // true
console.log(`myObj.hasOwnProperty('toString'): ${myObj.hasOwnProperty('toString')}`); // false你看,
in
hasOwnProperty
myObj
toString
in
hasOwnProperty
当然有,JavaScript提供了好几种内省机制来帮助我们理解对象的结构。不过,它们通常用于更高级的场景,或者获取更详细的信息,而不仅仅是判断“是不是原型属性”。
一个很有用的方法是
Object.getPrototypeOf()
[[Prototype]]
Object.getOwnPropertyDescriptor()
function Vehicle() {}
Vehicle.prototype.wheels = 4;
function Car() {}
Car.prototype = Object.create(Vehicle.prototype); // Car 继承自 Vehicle
Car.prototype.constructor = Car;
Car.prototype.engine = 'V6';
const myCar = new Car();
myCar.color = 'red';
let currentProto = Object.getPrototypeOf(myCar); // 获取 myCar 的直接原型 (Car.prototype)
const propName = 'wheels';
let foundOnPrototype = false;
while (currentProto) {
if (Object.prototype.hasOwnProperty.call(currentProto, propName)) {
console.log(`${propName} 在 ${currentProto.constructor.name}.prototype 上找到。`);
foundOnPrototype = true;
break;
}
currentProto = Object.getPrototypeOf(currentProto); // 继续向上查找原型链
}
console.log(`'${propName}' 是原型属性吗?${foundOnPrototype}`); // true
// 检查一个实例属性
currentProto = Object.getPrototypeOf(myCar);
const instancePropName = 'color';
foundOnPrototype = false;
while (currentProto) {
if (Object.prototype.hasOwnProperty.call(currentProto, instancePropName)) {
foundOnPrototype = true;
break;
}
currentProto = Object.getPrototypeOf(currentProto);
}
console.log(`'${instancePropName}' 是原型属性吗?${foundOnPrototype}`); // false这种手动遍历原型链的方式,虽然比
hasOwnProperty
另外,
Object.getOwnPropertyDescriptor(obj, propName)
value
writable
enumerable
configurable
Object.getOwnPropertyDescriptor(obj, propName)
undefined
Object.getOwnPropertyDescriptor
在日常开发中,区分实例属性和原型属性并非只是为了满足好奇心,它在很多实际场景中都有着重要的意义。
一个非常典型的场景就是对象的序列化和深拷贝。当我们想把一个JavaScript对象转换成JSON字符串(比如通过
JSON.stringify()
for...in
for...in
hasOwnProperty
// 错误的深拷贝尝试 (会把原型属性也拷贝过去)
function badDeepClone(obj) {
const newObj = {};
for (const key in obj) {
// 缺少 hasOwnProperty 检查
if (typeof obj[key] === 'object' && obj[key] !== null) {
newObj[key] = badDeepClone(obj[key]);
} else {
newObj[key] = obj[key];
}
}
return newObj;
}
// 正确的深拷贝,只拷贝实例属性
function goodDeepClone(obj) {
if (typeof obj !== 'object' || obj === null) {
return obj;
}
const newObj = Array.isArray(obj) ? [] : {};
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) { // 关键:只处理自身属性
if (typeof obj[key] === 'object' && obj[key] !== null) {
newObj[key] = goodDeepClone(obj[key]);
} else {
newObj[key] = obj[key];
}
}
}
return newObj;
}此外,在框架或库的开发中,这种区分更是基础。例如,当你设计一个继承体系时,你可能希望某些方法是共享的(放在原型上),而某些数据是每个实例独有的(放在实例上)。精确地控制属性的归属,能帮助你避免意外的数据共享问题,或者在调试时快速定位问题。
再比如,防止意外覆盖。如果你在对象实例上定义了一个与原型上同名的属性,那么实例属性会“遮蔽”原型属性。了解这一点,能帮助你避免无意中覆盖了原型上重要的方法或属性,从而导致程序行为异常。
总的来说,理解并能准确判断属性的来源,是深入理解JavaScript对象模型和原型链的关键一步。它不仅仅是理论知识,更是编写健壮、可维护代码的实际工具。
以上就是js如何判断属性是否在原型上的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号