+6

JS object and function. Script output.

Please explain, how does this script work? var x = 3; var a = { x:2, b: { x:1, c:function(){ return this.x; } } }; var go = a.b.c; alert(go()); alert(a.b.c()); output: 31 https://code.sololearn.com/WOqv0iE9JNpX/#js

4/19/2019 12:30:18 PM

Vladimir Maznev (Tomsk)

2 Answers

New Answer

+11

var x = 3; //assign 3 to variable x //assign a complex object to var a var a = { x:2, //put 2 in property x; same as a.x = 2 after creating a from outside b: { // This is a label, like a function x:1, // set property a.b.x=1 c:function(){ //label to an anoynoumous function return this.x; //return (current object).x } } }; var go = a.b.c; // assign the method a.b.c which returns this.x alert(go()); // returns 3 as this.x refers to window.x (var x) because go was defined in the global scope and 'this' refers to the window object. alert(a.b.c()); //returns 1 as the current object (a.b.c) finds the property x:1 inside a.b //colon https://stackoverflow.com/a/418805 //label https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label#Labeled_function_declarations //this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this //scope https://scotch.io/tutorials/understanding-scope-in-javascript

0

Clean