0

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

2 Answers 2

3

Redundancy is good for this:

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

Demo of it in action

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah this works ... only annoying thing is, that VS2013 intellisense only sees the "getAge" - any idea why VS's intellisense doesn't see both?
My bad - VS sees it fine now. Dunno why it didn't before. Thanks a million!
0

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/

6 Comments

NoDV, but answering a question, that isn't tagged with jQuery, with jQuery is a bad idea. See also this
@NiettheDarkAbsol althrough I agree the tag is missing, the OP uses jQuery in his example. I'm not saying he should use jQuery.
Well since I'm a noob on this, I would love to know all my choices wether it's js og jquery.
While there's no denying this code will certainly work, it bothers me because it's needlessly inefficient to do something in jQuery when the same thing in JavaScript is so readily available :)
Both examples work fine, althrough the example of NiettheDarkAbsol works always, regardless of the file order; jquery.extend only works after you declared the variable my. It's the only downside I can come up with. Althrough I got to say the jquery code looks cleaner.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.