简体   繁体   中英

javascript - access properties of this defined in outer function

I've experimented with closures and found unexpected behaviour. Can somebody explain why this code works this way, please?

function foo() {
    this.a='hello';
    return {
      aaa:function() {
        return a; // this suprises me, how can be here accessed 'a' ?
      }
  }
}

o=foo();
alert(o.aaa()); // prints 'hello' ! , I expected undefined

I don't understand, why I always use var that=this phrase, If it is possible to access function properties from inner functions directly.

jsfiddle https://jsfiddle.net/5co6f707/

It displays 'hello' because you're not in strict mode, so this is the global window object instead of undefined, and a becomes a global variable when you assign a value to this.a . Since a is a global variable it is accessible everywhere. You could just alert(a); at the very end of your script and it would also display 'hello' : https://jsfiddle.net/5co6f707/1/ .

It shouldn't work (and doesn't in strict mode) and it shouldn't be used. If you intend to use foo as a constructor then you should use the new keyword when you call it (which would break your code, but in a good way).

When this code is executed:

o=foo();

foo is executed in global context and so this line:

this.a='hello';

adds a property to the global object - window .

When you call your aaa function like this:

o.aaa()

the variable a is not defined within the function so it's looked up on up the scope chain and it's found on window:

function() {
     return a; // found on window.a
}

and so window.a is returned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM