0

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();

2 Answers 2

2

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.

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

Comments

0
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

Comments

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.