5
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.

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
user3763367
  • 127
  • 2
  • 7

5 Answers5

5

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.

Roman Kolpak
  • 1,942
  • 21
  • 25
0

Drop the prototype.
Replace:

x.prototype.mad = function() {

With:

x.mad = function() {

This simply adds a mad property to the object.

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
  • Now my question is, does prototype not work with object created using object literal? – user3763367 Sep 24 '14 at 11:05
  • For an explanation on what the `prototype` is, and how it works, I'd suggest having a look **[at this SO post](http://stackoverflow.com/questions/572897/how-does-javascript-prototype-work)**. `prototype` does not work with object literals like this, no. – Cerbrus Sep 24 '14 at 11:09
0

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");
}
Vishwanath
  • 6,284
  • 4
  • 38
  • 57
0

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.

Suma
  • 33,181
  • 16
  • 123
  • 191
Yuval A.
  • 5,849
  • 11
  • 51
  • 63
0
x.constructor.prototype.mad = function() {
   alert("USA");
};
x.mad();
Ali
  • 107
  • 1
  • 8