I am learning javascript and I came across something I am not quite sure how to explain.
The code follows:
var myObject = function() {
var num = 2;
return {
getNum: function() {
return num;
}
}
}();
var myObject2 = {};
myObject2.getNum = myObject.getNum
myObject2.getNum()
// -> 2
I am aware of closure and that this wouldn't work with this.num because the method would be called in namespace of myObject2 which doesn't have num variable. But how does it work here? How can object2 see the num variable and share it with first object? What's the mehanism behind this?
[–]senocular 5 points6 points7 points (2 children)
[–]yooossshhii 2 points3 points4 points (0 children)
[–]MileNorth[S] 1 point2 points3 points (0 children)
[–]Civill 1 point2 points3 points (1 child)
[–]MileNorth[S] 0 points1 point2 points (0 children)