0

let as opposed to var is scoped more tightly than var but I was wondering if it changes the scoping of anonymous functions?

Example:

class Foo {
    method1() {
        var scopelessFunc = this.method2;

        // executed in global scope
        scopelessFunc();

        let differentScope = this.method2;

        // what scope is this executed in?  (what does method2 output)
        differentScope();
    }

    method2() {
        console.log(this);
    }
}

NOTE: as of today jan 14 to my knowledge let is not fully supported anywhere so I can not go and test this myself.

6
  • 1
    let only declares where a variable will be visible. No more, no less.
    – zerkms
    Commented Jan 15, 2015 at 2:03
  • 3
    this is still the global object, it has nothing to do with lexical scope. this will depend on how you call the function.
    – elclanrs
    Commented Jan 15, 2015 at 2:05
  • 1
    this is based on how you call a function, not where it's called from. It's always resolved in the current execution context (except for arrow functions in ES6, which use the outer context's this).
    – RobG
    Commented Jan 15, 2015 at 2:07
  • And no, the scope in which a function was called never affected the scope of the executed function itself.
    – Bergi
    Commented Jan 15, 2015 at 2:07
  • thank you! cool, I learned something today! if one of you guys post this as an answer i can accept it or I will just delete the question.
    – dtracers
    Commented Jan 15, 2015 at 2:11

1 Answer 1

1

You're mixing up two concepts which have nothing to do with one another. Variable scoping via let and var just influences the visibility of those variables. The magic keyword this is a completely separate mechanism. What this refers to depends on how the function was invoked. Both scopelessFunc() and differentScope() invoke the function in exactly the same way, so there's no difference. If you want to make a difference, you need to change the way you call them:

someObj.scopelessFunc()
scopelessFunc.apply(someObj)

That's the only thing that influences this, and it doesn't matter whether someObj or scopelessFunc where defined via var or let.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.