简体   繁体   中英

Module Pattern Error in ES6 (Augmentation)

I'm getting an error while using module pattern (Augmentation) with ES6 let keyword.

This works.

var Example = ( Example => {
    Example.name = "";
    return Example;
})( Example || {} );

console.log(Example);

This does not.

let Example = ( Example => {
    Example.name = "";
    return Example;
})( Example || {} );

console.log(Example);

I'm getting this error.

Uncaught ReferenceError: Example is not defined

})( Example || {} );
    ^^^^^^^

The answer becomes fairly clear when you realize that this:

var x = (j => j)(x)

..becomes this:

var x = undefined
x = (j => j)(x)

It really declares x as undefined before evaluating the expression and setting x to the result.

However, let doesn't have that property - it's not hoisted:

let y = (j => j)(y)

..gets evaluated as just that.

y doesn't exist when you do (j => j)(y) , so it throws a reference error.

var declarations are hoisted , meaning that the name is considered "declared", but undefined until assigned within the entire function scope (as opposed to block scope). On the contrary, ES6 let declarations are not hoisted, so referencing Example causes the ReferenceError since it has not been declared yet.

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