Wednesday, 7 June 2017

javascript - When you pass 'this' as an argument

I'm trying to learn about this, and it's confusing me a bit here:




var randomFunction = function(callback) {
var data = 10;
callback(data);
};

var obj = {
initialData: 20,
sumData: function(data) {
var sum = this.initialData + data;
console.log(sum);

},
prepareRandomFunction: function() {
randomFunction(this.sumData.bind(this));
}
};

obj.prepareRandomFunction();


Is this designed to set itself where it is first rendered in code? For instance, in my example I'm successfully using it to refer to obj and also binding the function to obj, but since this is being passed as a callback function, what is stopping it from being set as randomFunction (i.e. what's stopping it from literally passing "this.sumData.bind(this)" so that this is set to randomFunction when it gets called from there)?




I'm a noob trying to learn. Thanks.



Updated
I'm not exactly asking how this works generally (I don't think). I'm mainly curious to know why this gets set where I define it as the argument of my randomFunction call, and not where callback gets called within randomFunction. I could be wrong, but if I were to swap this.sumData.bind(this) with the callback(data) that I currently have I think I would get a different result. Is that because callback is a reference to this.sumData.bind(this) when it was first defined (and where this is obj)?






I think I've learned through this scenario that this is set when it's executed. It's not passed as a argument to be set later when the argument is called down the line.

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...