Why was block scope not originally implemented in JavaScript?

前端 未结 4 1754
闹比i
闹比i 2020-11-29 01:23

I have read, and discovered through my own experience, that JavaScript doesn\'t have a block scope. Assuming that the language was designed this way for a reason, can you ex

4条回答
  •  借酒劲吻你
    2020-11-29 01:48

    Block scope was not implemented for the following reasons:

    1. It's makes the language easier to implement. JavaScript was initially designed as a language for writing interactive web applications. Hence it needed to be small and easy to implement.
    2. Block scopes introduce a performance hit to dynamic languages like JavaScript. This is because when you try to access some variable which is not in the current scope JavaScript first checks the current scope, then the parent scope and so on until it either finds the variable or reaches the end. Hence the introduction of block scopes would make variable access in loops and nested loops very slow.
    3. The lack of block scopes makes it easier to write programs. For example say you want to create a variable only if a certain condition is true. All you need to do in JavaScript is declare and define the variable within an if statement. In languages like C you would have to declare the variable outside the if statement and define it within the if statement.
    4. The lack of block scopes allow declarations to be hoisted. This is especially useful in the case of function declarations. For example see this fiddle: http://jsfiddle.net/L6SgM/ (note however that this example doesn't work in Firefox).
    5. Since JavaScript supports first-class function expressions we don't need block scopes. They can be simulated using immediately invoked function expressions.

提交回复
热议问题