MojoDK
MojoDK

Reputation: 4528

(Partial) Extending "functions" in javascript?

I have this code...

var my = {    
    helpers: {        
        getName: function() {
            return 'John Doe';
        }       
    }    
}

// in another file...

var my = {    
    helpers: {        
        getAge: function() {
            return '40';
        }       
    }    
}

// Test...

$("#myDiv").html(my.helpers.getName + " " + my.helpers.getAge);

http://jsfiddle.net/MojoDK/8cmV7/

... but getName is undefined.

I was hoping javascript was smart enough to merge it into this...

var my = {    
    helpers: {        
        getName: function() {
            return 'John Doe';
        },
         getAge: function() {
            return '40';
        }
    }    
}

How do I extend a method (or what it's called) like above? I have several "helper" files, that needs to "merge".

Upvotes: 0

Views: 57

Answers (2)

Billy Blaze
Billy Blaze

Reputation: 333

You can also use http://api.jquery.com/jquery.extend

as in:

var my = {
    getName: function() {}
};
$.extend(my, {
    getAge: function() {
    }
});

Demo: http://jsfiddle.net/7KW3H/

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324630

Redundancy is good for this:

my = window.my || {};
my.helpers = my.helpers || {};
my.helpers.getAge = function() {
    return 40;
};

Demo of it in action

Upvotes: 3

Related Questions