JavaScript检查对象是否继承了属性

JavaScript check if object has inherited property

本文关键字:属性 继承 是否 检查 对象 JavaScript      更新时间:2023-09-26
function Employee(name, dept) {
    this.name = name || "";
    this.dept  = dept || "general";
}
function WorkerBee(projs) {
    this.projects = projs || [];
}
WorkerBee.prototype = Object.create( Employee.prototype );
function Engineer(mach) {
    this.dept = "engineering";
    this.mach = mach || "";
}
Engineer.prototype = Object.create(WorkerBee.prototype);
var jane = new Engineer("belau");
console.log( 'projects' in jane );

正在尝试检查jane是否继承了projects属性。

输出false。为什么?

输出false。为什么?

因为this.projects被设置在WorkerBee内部,但该函数从未被执行。

这与您之前的问题相同:JavaScript继承Object.create((未按预期工作

如果您正在测试对象本身(而不是其原型链的一部分(上的属性,则可以使用.hasOwnProperty((:

if (x.hasOwnProperty('y')) { 
  // ......
}

对象或其原型具有属性:

您也可以使用in运算符来测试继承的属性。

if ('y' in x) {
  // ......
}