user2990798
user2990798

Reputation: 21

calling a string as function call in javascript

What is wrong in this ?? I want to call a string as a function. Could someone please help me on this

var wnameSpace = (function(){  
    var privateVar = '';
    privateVar = "dummyFunction";  
    dummyFunction = function(){
        console.log("hurray dummyFunction called here");
    };  
    return {
        publicFunction:function() {
            console.log(window[wnameSpace])
        }  
    } 
})();

wnameSpace.publicFunction();

Upvotes: 0

Views: 56

Answers (2)

user2990798
user2990798

Reputation: 21

var wnameSpace = (function(){ 
var privateVar = ''; 
privateVar = "dummyFunction"; 
dummyFunction = function(){ 
console.log("hurray dummyFunction called here"); 
}; 
return { 
publicFunction:function(){ 
var fn = window[privateVar]; if (typeof fn === "function") fn(); 
} 
} 
})(); 

wnameSpace.publicFunction();

Will also work.. Thank you for all the anwsers

Upvotes: 0

p.s.w.g
p.s.w.g

Reputation: 149020

Well, you're accessing window[wnameSpace] but I think you meant to use window[privateVar]. Also, you probably meant to invoke the function rather than just log it. Try this:

var wnameSpace = (function(){  
    var privateVar = "dummyFunction";  
    dummyFunction = function(){
        console.log("hurray dummyFunction called here");
    };  
    return {
        publicFunction:function() {
            window[privateVar](); // "hurray dummyFunction called here"
        }  
    } 
})();

wnameSpace.publicFunction();

However, I wouldn't recommend using this kind of code in production. It's hard to tell what you want, exactly, but I'm pretty sure there is a better way to accomplish it.

Upvotes: 2

Related Questions