Extending object literal

两盒软妹~` 提交于 2020-01-24 10:47:08

问题


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.


回答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.

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.




回答2:


Drop the prototype.
Replace:

x.prototype.mad = function() {

With:

x.mad = function() {

This simply adds a mad property to the object.




回答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");
}



回答4:


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



回答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.



来源:https://stackoverflow.com/questions/26015216/extending-object-literal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!