Extending Object Literal
Solution 1:
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.
functionMyObj() {}
MyObj.prototype.foo = function() {
// ...
}
var myObj = newMyObj();
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.
Solution 2:
Drop the prototype
.
Replace:
x.prototype.mad = function() {
With:
x.mad = function() {
This simply adds a mad
property to the object.
Solution 3:
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");
}
Solution 4:
x.constructor.prototype.mad = function() {
alert("USA");
};
x.mad();
Solution 5:
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.
Post a Comment for "Extending Object Literal"