user3763367
user3763367

Reputation: 147

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.

Upvotes: 5

Views: 2996

Answers (5)

Yuval A.
Yuval A.

Reputation: 6109

This also works, by the way:

Object.prototype.mad = function() {
    alert("USA");
}

var x = {
    name: "japan",
    age: 20
}

x.mad();

But then, the mad function will be part of any object what so ever, literals, "class" instances, and also arrays (they have typeof === "object"). So - you'll probably never want to use it this way. I think it's worth mentioning so I added this answer.

Upvotes: 0

Ali
Ali

Reputation: 107

x.constructor.prototype.mad = function() {
   alert("USA");
};
x.mad();

Upvotes: 0

Roman Kolpak
Roman Kolpak

Reputation: 2022

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.

Upvotes: 5

Vishwanath
Vishwanath

Reputation: 6004

You dont have .prototype available on anything but function object. So your following code itself fails with error TypeError: Cannot set property 'mad' of undefined

x.prototype.mad = function() {
    alert("USA");
};

If you need to use prototype and extension, you need to use function object and new keyword. If you just want to add property to your object. Assign it directly on the object like following.

x.mad = function() {
     alert("USA");
}

Upvotes: 0

Cerbrus
Cerbrus

Reputation: 72967

Drop the prototype.
Replace:

x.prototype.mad = function() {

With:

x.mad = function() {

This simply adds a mad property to the object.

Upvotes: 0

Related Questions