Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I extend properly a JS object?

Let's say I have something like this in a file named main.js:

function obj_name() {}

obj_name.prototype = {
    foo  : function() { alert('hi!'); },
    foo2 : function() { alert('hi again!'); }
}

Now I am trying this way to expand the object in another file extend.js:

obj_name.prototype = {
    newfoo : function() { alert('hi #3'); }
}

... but the problem is that it will just work if I code it this way:

obj_name.prototype.newfoo = function() { alert('hi #3'); }

I guess this may be a noob question. I don't even know if this is the proper way to extend an object, but I am freaking out here wondering why does this happen.

Thank you guys in advance.

like image 957
jmic Avatar asked May 12 '11 08:05

jmic


People also ask

Can we extend function in JavaScript?

First let us extend javascript function. We can also create Javascript Function by extending Javascript classes, like this. Let us extend this class with Child function like this, function Child(props) { let parent = new BaseClass(props) const getMessage = () => `Message is ${parent.

Can you modify an object in JavaScript?

Using the same method, an object's property can be modified by assigning a new value to an existing property. At this point, if we call the object, we will see all of our additions and modifications. Through assignment operation, we can modify the properties and methods of a JavaScript object.

Is it possible to extend built-in classes in JS?

Array, Map, and other built-in classes are extendable. The most impressive thing is that built-in methods such as map , filter, and more - return new objects of literally the inherited type NumsArray .


1 Answers

Another option without jQuery:

var extend = function(destination, source)
{
    for (var property in source)
    {
        if (destination[property] && (typeof(destination[property]) == 'object')
                && (destination[property].toString() == '[object Object]') && source[property])
            extend(destination[property], source[property]);
        else
            destination[property] = source[property];
    }
    return destination;
}

var a = {a: 'test'};                              // original
var b = {newFoo: function() { alert('hi #3'); }}; // the addition
extend(a, b);                                 // extend it
a.newFoo();                                   // call the added property
like image 100
tradyblix Avatar answered Oct 06 '22 10:10

tradyblix