开发者

Why isn't it possible to dynamically create a variable via self-invoking function in Javascript?

开发者 https://www.devze.com 2023-03-11 03:40 出处:网络
I\'m trying to imita开发者_开发百科te some sort of constructor like in other programming languages.

I'm trying to imita开发者_开发百科te some sort of constructor like in other programming languages. If I do it like this it doesn't work. :/ Sorry for being dumb! :/ Thanks for the help!!

  function foo(){

      this.makeVar = function(){this.newVar = 'hello world'}(); 

  }

 var test = new foo();
 alert(test.newVar); 


Because you are calling the (anonymous) function directly, and not as a method on an object. So this is window.

Copy the value of this in the outside function to a variable that is still available on the inside function.

function foo(){
  var self = this;
  this.makeVar = function(){
    self.newVar = 'hello world';
  }(); 
}


Don't apologise for "being dumb". Asking questions is actually smart (usually).

The function foo() already is a constructor, so there's no need for an internal constructor's constructor.

0

精彩评论

暂无评论...
验证码 换一张
取 消