2
var Person = function(name, age){
    return Object.create(Object.prototype, {
        name: {
            value: name | "",
            writable: true,
            enumerable: true,
            configurable: true
        },
        age: {
            value: age | "",
            writable: true,
            enumerable: true,
            configurable: true
        }
    });
};

var Boy = function(name, age){
    return Object.create(Person(name, age), {
        gender: {
            value: "male"
        }
    });
};

var p = Person("John", 28);
var b = Boy();

console.log(p.isPrototypeOf(b)); // false?

I'm trying to understand object.create and how best to use it avoiding use of constructors the new keyword. So far I am approaching it as above (although probably not the best way, just trial and error) - and came across that if I use object.create I am no longer able to check instanceof and object type.

Someone suggested using isPrototypeOf to check - I'm doing something wrong as my code above returns false when checking.

Would anyone be kind enough to explain where I am going wrong? I'm still new to prototypal inheritance in javascript.

hippietrail
  • 15,848
  • 18
  • 99
  • 158
leepowell
  • 3,838
  • 8
  • 27
  • 35

1 Answers1

2

Of course p is not a prototype of b.

That's because the Person function returns a new Object each time.

Try the following

var Boy = function(person, name, age){
    return Object.create(person, {
        gender: {
            value: "male"
        }
    });
};


var p = Person("John", 28);
var b = Boy(p);
assert(p.isPrototypeOf(b))
Raynos
  • 166,823
  • 56
  • 351
  • 396