user1801359
user1801359

Reputation: 422

Why is object data undefined in method?

I have some code that isn't working and I don't understand why. I boiled it down to this simple example:

function Load() {
    this.data = {
        isLoaded: false,
    };

    this.load1 = function() {
        console.log(this.data.isLoaded);
    };

    this.system = {
        load2: function() {
            console.log(this.data.isLoaded);
        }
    };
}

let a = new Load();
a.load1();
a.system.load2();

Why is this.data defined in the load1 function but undefined in the load2 function? Is there a way to get it working with the structure that I want (the second form)?

Thanks.

Upvotes: 0

Views: 583

Answers (4)

Dien Phan
Dien Phan

Reputation: 1

It will work when you explicitly bind the context: a.system.load2.call(a);

Upvotes: 0

Derek Wang
Derek Wang

Reputation: 10204

This will work. Put this.data into function scope variable called parentData and you can use that value on any child.

this in this.system.load2 refers this.system content and it won't call parent data.

function Load() {
  this.data = {
    isLoaded: false,
  };
  
  var parentData = this.data;

  this.load1 = function() {
    console.log(this.data.isLoaded);
  };

  this.system = {
    load2: function() {
      console.log(parentData.isLoaded);
    }
  };
}

let a = new Load();
a.load1();
a.system.load2();

Upvotes: 1

Bulent
Bulent

Reputation: 3411

It's always a good idea to run console.log(this). It's all about what "this" refers to.

Upvotes: 2

Jack
Jack

Reputation: 99

I believe this has to do with scoping.

this.data.isLoaded is referring to the current scope of load2

this.system = {
        load2: function() {
            console.log(this.data.isLoaded);
        }
    };

Upvotes: 0

Related Questions