Skip to content Skip to sidebar Skip to footer

How Can I Attach Prototype To Object Literals In JS

I am trying to understand JavaScripts Prototypal nature and I am trying to create object inheritance without using class like constructor functions. How can I attach the prototype

Solution 1:

You can use Object.create to use your defined objects as prototypes. For instance:

var Dog = Object.create(Animal, {
    bark : {
        value: function() {
            console.log("Woof! My name is " + this.name);
        }
    }
});

Now you can create a new Dog object:

var myDog = Object.create(Dog);
myDog.bark();  // 'Woof! My name is null'
myDog.getColor();  // 'The hair color is null'

Example: http://jsfiddle.net/5Q3W7/1/

Alternatively, if you're working in the absence of Object.create, you can use constructors:

function Animal() {
    this.name = null;
    this.hairColor = null;
    this.legs = 4;
};

Animal.prototype = {
    getName : function() {
        return this.name;
    },
    getColor : function() {
        console.log("The hair color is " + this.hairColor);
    }
}

function Dog() {
}

Dog.prototype = new Animal;
Dog.prototype.bark = function() {
    console.log("Woof! My name is " + this.name);
};

Example: http://jsfiddle.net/5Q3W7/2/

For more information about Object.create: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/create/

For more information about Constructors and prototypes chains: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/constructor

https://developer.mozilla.org/en/JavaScript/Guide/Inheritance_and_the_prototype_chain


Solution 2:

edit: Totally overlooked Object.create. @jMerliN's answer is more appropriate, unless you need more extensive backwards compatibility.


Animal, Cat and Dog do share Object.prototype since they are instances of Object but that's not where you want to put your methods.

You can mimick inheritance by using an extend function:

var Dog = {
    bark : function() {
        console.log("Woof! My name is ")
    }
}

jQuery.extend(Dog, Animal)

That could be underscore's _.extend or your own extend function, which simply copies over it's properties:

function extend(obj, source){
    for (var prop in source) {
        obj[prop] = source[prop]
    }
} 

Be careful with references though: "primitive" values like strings, numbers, booleans will be copied over, while objects, functions and arrays will be referenced:

var Animal = {
    tags: [1,2,3]
}

var Dog = {
    //...
}

_.extend(Dog, Animal)

Dog.tags.push(4)

Dog.tags // [1,2,3,4]
Animal.tags // [1,2,3,4] oh no!

There's no reason to go through this, it's error prone and less memory-efficient; just use constructors :)


Post a Comment for "How Can I Attach Prototype To Object Literals In JS"