+ 8
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
2 Answers
+ 14
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
+ 2
Я конечно не уверен что в тему, но вот какие варианты бы я предложил :
var x = 3;
var a = {
x:2,
b: {
x:1,
//тот же вариант но с параметром - объекта применения
f1:function(self){
return self.x;
},
//вариант с свойством для привязки функции
f2:null,
//вариант с методом обёрткой куда будет передана функция
f3:function(pf){
return pf(this);
}
}
};
var go = a.b.f1;
alert(go(a.b));
alert(a.b.f1(a.b));
a.b.f2 = a.b.f1;
alert(a.b.f2(a.b));
alert(a.b.f3(go));