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.

1 Answer 1

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.