1
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 );

Trying to check if jane inherited the projects property.

Outputs false. Why?

Robert
  • 10,126
  • 19
  • 78
  • 130

2 Answers2

3

Outputs false. Why?

Because this.projects is set inside WorkerBee, but that function is never executed.

This is the same issue as in your previous question: JavaScript inheritance Object.create() not working as expected

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

If you are testing for properties that are on the object itself (not a part of its prototype chain) you can use .hasOwnProperty():

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

Object or its prototype has a property:

You can use the in operator to test for properties that are inherited as well.

if ('y' in x) {
  // ......
}
Robin
  • 471
  • 6
  • 18
  • While you are right, this doesn't answer the OP's question. – Felix Kling Jun 24 '15 at 00:00
  • `x = "test"; try { if ('indexOf' in x) { console.log('it is correct answer'); }} catch (e) {console.log('it is wrong answer, actually'); }` – OZ_ Nov 09 '20 at 09:04