1

I have the following code (simplified)

var Page = new UI('page.html');

Page.onLoad = function(html){

    this.name = 'Page 1';
    Util.test(this.run);

};

Page.run = function(){

    console.log(this.name); // undefined
    console.log(Page.name); // correct

};

var Util = function(){};

Util.prototype.test = function(callback){

    // when finished run the callback
    callback();

};

My question is why I can't use the this keyword if the execution leaves the object then comes back? Please explain what should I change to be able to access this again.

slash197
  • 8,782
  • 6
  • 38
  • 68
  • Maybe your `.run` is executed first and only than `.onLoad` that sets `this.name`? Also maybe your UI page does not bind `this` to function and it's always the function itself? – Justinas Feb 03 '17 at 08:09
  • @Justinas if that was the case `Page.name` would be undefined as well, I think – slash197 Feb 03 '17 at 08:10

2 Answers2

0

The top of the article references another post regarding 'this', so, I thought I'd just provide the code. If you read the other post and the articles linked within, you should be able to follow this code.

function UI(html) {
    this.name = html;
}

UI.prototype = {

    onLoad: function () {
        util.test(this);
    },

    run: function () {
        console.log(this.name);
    }
}

var util = (function () {
    return {
        test: function (ui) {
            if (ui && ui.run) {
                ui.run();
            }
        }
    }
})();

var page = new UI("index.html");
Mark Graham
  • 171
  • 6
0

You can bind "this" to function run, like this.

Page.onLoad = function(html){

    this.name = 'Page 1';
    Util.test(this.run.bind(this));

};

You can find more information for function "bind". https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

Igor Dolzhenkov
  • 579
  • 4
  • 4