1

If you have something like that :

var ASK = (function (){
   var i = 0, _this = this;
   function private(){
      console.log(i++)
   }
   return {
      call : function (methodName, args){
         eval(methodName + '(' + args + ')' );
      }
   }
})();

ASK.call('private');

It's possible to call a function inside ASK scope without using eval ? And why when i try use _this[method]() I get that it's not a function ? Does _this shouldn't refer to scope inside ASK = (function(){})?

3 Answers 3

3

Use object:

var ASK = (function (){
   var i = 0, _this = this;
   var myFuncs = {
       private: function(){
          console.log(i++)
       }
   }
   return {
      call : function (methodName, args){
         myFuncs[methodName](args);
      }
   }
})();

ASK.call('private');
Sign up to request clarification or add additional context in comments.

4 Comments

For completeness let me also clarify that _this isn't anything useful here, see my post
You don't have the new operator anywhere, what do you think this should be?
new totally isn't relevant for this, it's only needed for prototypes (and still not necessary since Object.create was introduced).
Yes... you are right. I mean at the point of this usage, there is no any new object. In the your code you have {}, which in fact is a synax sugar for the new Object(). ideone.com/kqpBT
0

Does _this shouldn't refer to scope inside ASK = (function(){})?

Nope. You aren't calling that anonymous function "through" any object which this could refer to, so _this ends up equal to window / undefined (depending on strict mode).

You're probably confused over how this works in JS. Please have a google on that for many good explanations.

Refer to @kan's code snippet for how to solve this and note that closures actually solve the local variable scoping problem for you, so you don't really need to be concerned about this here.

Comments

0

http://jsfiddle.net/WCN5n/
http://jsfiddle.net/BkTDz/
http://jsfiddle.net/QgFfF/

1 Comment

Please add content as well as just links

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.