+ 2

what's happened

"use strict"; class a {}; alert (a in window); alert (b in window); // true var b = class { constructor(name) { this.name = name; } say() { return this.name } }; let c = class {}; alert (a in window); alert (b in window); // false??? alert (c in window); alert ( new window.b('SMITH').say() ); // всё работает

4th May 2017, 4:09 PM
░S░M░I░T░H░
░S░M░I░T░H░ - avatar
3 Antworten
+ 4
To understand this, you have understand how Javascript engine runs the code in background and variable and function hoisting. Javascript engine take two step to execute/run your code. 1: Parse time and 2: Run time 1: Parse time ------------- In this step engine doesn't run your code, It check your code syntax error and only store the variable and function declaration to memory. Remember that variable assigned value doesn't get to store into memory in this step, only declaration. 2: Run time ----------- In this step engine will assign variable assigned value in memory and execute/run your code line by line (top to bottom). REMEMBER: ==> ES6 let, const, class are global ( if you declare it globally) but they are not property of global object. ==> Javascript "in" operator check for index and property name in object ==> Property name are stored as a string in Javascript ==> "in" operator returns true for "undefined" and "0" stored window window object POSSIBLE EXPLANATION OF YOUR CODE --------------------------------- "use strict"; class a {}; alert (a in window); // false //a is class here, it is not property of global object. so it returns false alert (b in window); // true // in parse time b is stored in memory with value of "undefined" // in runtime it finds that and return true ( check the REMEMBER section last item) var b = class { constructor(name) { this.name = name; } say() { return this.name } }; let c = class {}; alert (a in window); // false // same reason like above alert (b in window); // false // now value of b is a class not undefined or 0. so return false // since b is a declared with var keyword, it is a property of global object // use string property name to get true value, like this alert('b' in window); alert (c in window); // false // c is declared with let keyword, so it is not a property of global object alert ( new window.b('SMITH').say() ) // SMITH i will comment here a code project later. :)
4th May 2017, 5:43 PM
Apel Mahmod
Apel Mahmod - avatar
+ 4
Here is code project. you can check it for better understanding what happens in Javascript engine. https://code.sololearn.com/Wz9jMR9yJUGv/#js I am not a Javascript guru, so if you find anything inconsistent let me know. Thanks
4th May 2017, 6:06 PM
Apel Mahmod
Apel Mahmod - avatar
+ 2
thank you very mutch. It was useful information
4th May 2017, 6:30 PM
░S░M░I░T░H░
░S░M░I░T░H░ - avatar