-
Notifications
You must be signed in to change notification settings - Fork 8
Open
Description
EDIT:
The readme has been updated since this was first posted, however the changes made do not sufficiently address all of the scoping problems. Ref: 3280e50
Original follows the break
Re: the example from the readme:
// this ...
a {
...
b {
...
}
...
}
// ... is desugared to ...
a(function() {
...
this.b(function() {
...
})
...
});
-
What is
this
inside the callback function? In strict mode code, that desugaring has nothis
unless explicitly bound:"use strict"; function a(m, callback) { console.log(m); console.log(`inside a(): typeof this === ${typeof this}`); callback(); } function b(callback) { callback(); } a("hello", function() { this.b(function() { console.log(`(inside b(): typeof this === ${typeof this})`); }); }); // hello // (inside a(): typeof this === undefined) // Uncaught TypeError: Cannot read property 'b' of undefined
-
The example does work with non-strict mode code, but also assumes that
b
was created via VariableStatement or FunctionDeclaration in the top level scope:function a(m, callback) { console.log(m); console.log(`(inside a(): typeof this === ${typeof this})`); callback.call(this); } function b(callback) { callback(); } a("hello", function() { this.b(function() { console.log(`(inside b(): typeof this === ${typeof this})`); }); }); // hello // (inside a(): typeof this === object) // (inside b(): typeof this === object)
- If
b
was created as a LexicalDeclaration, it won't have a binding on globalthis
object:let a = function(m, callback) { console.log(m); console.log(`(inside a(): typeof this === ${typeof this})`); callback.call(this); }; let b = function(callback) { callback(); }; a("hello", function() { this.b(function() { console.log(`(inside b(): typeof this === ${typeof this})`); }); }); // hello // (inside a(): typeof this === object) // Uncaught TypeError: this.b is not a function
- That also means that this won't work in Module Code—which is strict mode code by default.
- If
-
(2) falls down when the user defined functions have an explicit
this
object set:var unbounda = function(m, callback) { console.log(m); console.log(`(inside a(): typeof this === ${typeof this})`); callback.call(this); }; var unboundb = function(callback) { callback(); }; var thisObject = {}; var a = unbounda.bind(thisObject); var b = unbounda.bind(thisObject); /* a("hello") { b { console.log(`(inside b(): typeof this === ${typeof this})`); } } */ a("hello", function() { this.b(function() { console.log(`(inside b(): typeof this === ${typeof this})`); }); }); // hello // (inside a(): typeof this === object) // Uncaught TypeError: this.b is not a function
Metadata
Metadata
Assignees
Labels
No labels