Javascript - object state

Maybe I'm wrong...

I am trying to track the state of objects inside myself and use it to call the modified methods:

createObject = function() {
  this.a = 1

  this.method1 = function() {
  if (this.a == 1 ) {
    //do stuff
    this.a = 0
  }
}

var x = new createObject()

Unfortunately, the state is not tracked internally. If I change the properties of another object, it works fine:

otherObj = { a:1 }

createObject = function() {

  this.method1 = function() {
  if (this.a == 1 ) {
    //do stuff
    otherObject.a = 0
  }

}

var x = new createObject()

Is this right?

+4
source share
1 answer

You have a problem because thisin method1()is different from thisin an external function. This is because a scope is created in JS functions.

First approach

So you may want to abe a variable, not a property this:

createObject = function() {
  // 'a' is now available here...
  var a = 1

  this.method1 = function() {
    // ... and here as well.
    if (a == 1 ) {
      a = 0
    }
  }
}

Second approach

this ( self ):

createObject = function() {
  // 'self' is a regular varialbe, referencing 'this'
  var self = this;
  this.a = 1

  this.method1 = function() {
    // Here, self !== this, because 'this' in method1() 
    // is different from 'this' in outer function.
    // So we can access 'self.a':
    if (self.a == 1 ) {
      //do stuff
      self.a = 0
    }
  }
}

, bind() this method1():

var createObject = function () {
    this.a = 1

    this.method1 = function () {
        console.log(this.a);
        if (this.a == 1) {
            this.a = 0
        }
    }.bind(this);
    // ^ note `bind(this)` above. Now, 'this' inside 'method1'
    // is same as 'this' in outer function.
}

bind(). , IE < 9.

+12

All Articles