MDN URL: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
In the section with the example code for Creating a bound function
The line below returns undefined not 9:
const retrieveX = module.getX;
retrieveX();
// returns 9; the function gets invoked at the global scope
_Examples_
_Creating a bound function_
undefined
console.log(retrieveX()); -> nodejs console in vs code
MDN Content page report details
en-us/web/javascript/reference/global_objects/function/bindWell... it threw an exception for me, since I always execute my code as a module.
But I pulled up an old Node running code as a script, ran it, and got 9. Not sure what's up with vscode's console.
Well... it threw an exception for me, since I always execute my code as a module.
Yeah, that would cause different behavior.
But I pulled up an old Node running code as a script, ran it, and got
9.
Yeah. The comments in the code examples in that article are correct.
That retrieveX() returns 9 in the Node.js REPL (v15.5.0):
$ node
Welcome to Node.js v15.5.0.
Type ".help" for more information.
> this.x = 9; // 'this' refers to global 'window' object here in a browser
9
> const module = {
... x: 81,
... getX: function() { return this.x; }
... };
> module.getX();
81
> // returns 81
> const retrieveX = module.getX;
> retrieveX();
9
> // returns 9; the function gets invoked at the global scope
> // Create a new function with 'this' bound to module
> // New programmers might confuse the
> // global variable 'x' with module's property 'x'
> const boundGetX = retrieveX.bind(module);
> boundGetX();
81
> // returns 81
…and also in browsers; e.g., In Firefox devtools:
> this.x = 9; // 'this' refers to global 'window' object here in a browser
> const module = {
> x: 81,
> getX: function() { return this.x; }
> };
> module.getX();
> // returns 81
> const retrieveX = module.getX;
> retrieveX();
> // returns 9; the function gets invoked at the global scope
9
Not sure what's up with vscode's console.
Me neither — but I guess it must it must be messing with the global scope somehow.
@unkn0wn3rr0r There’s no bug in the article, so I’m closing this. But feel free to still post more comments if you have anything further to add or ask.
Most helpful comment
Yeah, that would cause different behavior.
Yeah. The comments in the code examples in that article are correct.
That
retrieveX()returns9in the Node.js REPL (v15.5.0):…and also in browsers; e.g., In Firefox devtools:
Me neither — but I guess it must it must be messing with the global scope somehow.
@unkn0wn3rr0r There’s no bug in the article, so I’m closing this. But feel free to still post more comments if you have anything further to add or ask.