JavaScript检查对象是否具有继承属性

时间:2015-06-23 23:52:33

标签: javascript inheritance

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。为什么呢?

2 个答案:

答案 0 :(得分:3)

  

输出false。为什么呢?

因为this.projects设置在WorkerBee内,但该函数永远不会执行。

这与上一个问题中的问题相同:JavaScript inheritance Object.create() not working as expected

答案 1 :(得分:1)

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

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

对象或其原​​型具有属性:

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

if ('y' in x) {
  // ......
}
相关问题