Monday 3 April 2017

javascript - The magic of "var self = this", understanding scope and references

I am not new to javascript and its scopes, but I always wondered why the heck the following example actually works.



// lets define some twist
var ScopeMagic = function() {
// early reference, copy dat' value
var self = this;
// there is no real mystery yet...
this.mysteryDepth = 0;

// but we create one there...
this.increase = function(depth) {
// okay, its clear that the context is "this"
setMystery(depth);
return this;
};

// private function, setting a value to the "self" variable
function setMystery(val) {
// i though self would by a copy of "this" !
// mother Mary, i'm using self. I could use this here, but
// for the sake of the demo using self on purpose
self.mysteryDepth += parseInt(val);
}
}

var perplexity = new ScopeMagic();
perplexity.increase(42);
console.log(perplexity);


And we get the following result.



enter image description here



It works obviously, but how can the object property be modified when we set it by using a reference to self which appears to be a variable of its own (copy of this) ?

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...