Search code examples
javascriptprototypeobject-literal

Extending object literal


var x = {
    name: "japan",
    age: 20
}
x.prototype.mad = function() {
    alert("USA");
};
x.mad();

The above code does not work. object literals cannot be extended? or x.mad() not the right way to call.


Solution

  • You can't do it this way. To be able to define object methods and properties using it's prototype you have to define your object type as a constructor function and then create an instance of it with new operator.

    function MyObj() {}
    MyObj.prototype.foo = function() { 
        // ... 
    }
    
    var myObj = new MyObj();
    myObj.foo()
    

    If you want to keep using object literals, the only way to attach behaviour to your object is to create its property as anonymous function like so

    var myObj = { 
        foo: function() { 
           // ...
        }
    }
    
    myObj.foo(); 
    

    The latter way is the quickest. The first is the way to share behaviour between mutiple objects of the same type, because they will share the same prototype. The latter way creates an instance of a function foo for every object you create.