Search code examples
javascriptobject-create

Passing arguments when using Object.create as opposed to new


This question isn't a duplicate of Using "Object.create" instead of "new". The thread in question doesn't focus on passing arguments correctly when using Object.create


I am curious as to how I would go about initializing objects using Object.create as opposed to new. Here is my code so far:

function Human(eyes) {
    this.eyes = eyes || false;
}

Human.prototype.hasEyes = function() {
    return this.eyes;
}

function Male(name) {
    this.name = name || "No name";
}

Male.prototype = new Human(true); //passing true to the Human constructor

var Sethen = new Male("Sethen");

console.log(Sethen.hasEyes());

As you can see above, the Male.prototype = new Human(true); creates a new object with true. When the hasEyes() function is run, this logs true as expected.

So, my question is.. using Object.create how would I go about doing this the same way passing a true parameter??


Solution

  • You must call the constructor using Object.call(this) and then pass your arguments.

    function Human(eyes, phrase) {
        this.eyes = eyes || false;
        this.phrase = phrase;
    }
    
    Human.prototype.hasEyes = function() {
        return this.eyes;
    }
    
    Human.prototype.sayPhrase = function() {
        return this.phrase;
    }
    
    function Male(name) {
        Human.call(this, true, "Something to say"); //notice the call and the arguments
        this.name = name || "No name";
    }
    
    Male.prototype = Object.create(Human.prototype);
    
    var Sethen = new Male("Sethen");
    
    console.log(Sethen.hasEyes());
    console.log(Sethen.sayPhrase());
    
    console.log(Object.getOwnPropertyNames(Sethen));
    

    This works and now the object Male has the properties of eyes and phrase