0

I am confused about the way this behaves in some circumstances for example I have this code

var makeRequest=function(url,callback){

  var data=10; 

  callback(data);
};

var obj = {
  someValue: 20,
  loadData: function(data){
    var sum = this.someValue + data;
    alert(sum);
  },
  prepareRequest:function(){
    var url="http://someurl.com";

    makeRequest(url,obj.loadData);

  }
};

It makes a request let s say and it gets some data. The thing is when I call the function makeRequest with obj.loadData as parameter it gives an error. Can someone explain why it happens this? Why it doesn t behave the expected way when i call obj.prepareRequest() even tho the loadData method is attacked to obj object? I would appreciate any help. "This" keyword is really confusing.

Osiris
  • 107
  • 4
  • 14
  • 1
    Possible duplicate of [How does the "this" keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Peter Reid Jun 24 '17 at 14:42
  • What's the error you get? – Eduardo Melo Jun 24 '17 at 14:42
  • Within your function "loadData", "this" does not refer to your object, but the function itself. Read up on variable scope in JavaScript – EyeOfTheHawks Jun 24 '17 at 14:43
  • 2
    Functions, without explicit binding, are in no way permanently associated with objects. When you pass `obj.loadData` as the callback, the relationship to `obj` is lost. You can use `obj.loadData.bind(obj)` to create a function that *is* bound to the object. – Pointy Jun 24 '17 at 14:46
  • 1
    Maybe read [_this_](https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/ch2.md#chapter-2-this-all-makes-sense-now) – maazadeeb Jun 24 '17 at 14:50

1 Answers1

0

At the point when you passed your loadData function as a parameter into makeRequest just think of switching ownership ... makeRequest now owns loadData so if there's any this keyword being used in loadData then it is referring to makeRequest not obj .

The way to maintain ownership or context is to use .bind()

loadData has no clue what this.someValue is because the context was changed

In your prepareRequest function add bind and good practice is to use this for oop purposes

Example

makeRequest(url,this.loadData.bind(this));

Hope this helps

KpTheConstructor
  • 3,153
  • 1
  • 14
  • 22
  • So what you mean is that even though loadData is a method attached to the obj object because is also a parameter of makeRequest and since makeRequest is a function which is an object in javascript now loadData is attached to makeRequest object . Is what i understand so far. I hope i got it right – Osiris Jun 24 '17 at 16:54