开发者

calling inner variable of a function

开发者 https://www.devze.com 2023-03-25 17:03 出处:网络
Why is it that I have to use a new instance of a function in order to get an inner variable,开发者_JS百科 but I can\'t use the function itself,

Why is it that I have to use a new instance of a function in order to get an inner variable,开发者_JS百科 but I can't use the function itself,

why this works

function bla(){this.a = 1}
b = new bla
alert (b.a)

and this doesn't

function bla(){this.a = 1}
alert (bla.a)

?


Because you have to call the function in order for the variable to be defined.

If you want to do what you're talking about, you can use an object literal

var bla = 
{
  a: 1,

  displayA: function() {
    alert(bla.a);
  }
};

alert(bla.a); // Displays 1
bla.displayA(); // Displays 1


You have to create a new instance of the object. In this case, the first one works because you declare

b = new bla

Just a side tip, you should have wrote it more like this to prevent possible errors...

function bla(){this.a = 1;}
b = new bla();
alert(b.a);


Because when you use a function in that manner, you're effectively making an object with a property, and you cannot access a property of an object without instantiating the object with the new keyword.

You could do this, which would also return 1:

function bla(){ return 1;}
alert (bla());


What has not been pointed out is that in the case:

function bla(){this.a = 1}
alert (bla.a)

bla has not been called as a constructor nor as as a method of an object so its this keyword is set to the global/window object. Hence an a property is added to the global/window object and you can do:

alert(a)

but that is usually an undesirable result. In ES5 strict mode, calling a function this way will cause its this keyword to be undefined, so this.a will throw an error.

0

精彩评论

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