Make a variable available to methods within an object

Hello,

In PHP you would do something like this:



class Foo
{

  protected $zar;
  protected $bar;

  public function setZar($someValue)
  {

    $this->$zar = $someValue;

  }

  public function setBar($someValue)
  {

    $this->$bar = $someValue;

  }
  public function myMethodWhereEverythingHappens()
  {

    if ( $this->zar == $this->bar) {
        //...
    }

  }

}


Would it be correct to do the following in JS?



var Foo = {

  zar: '',
  bar: '',

  setZar: function(someValue){
    this.zar = someValue;
  },

  setBar: function(someValue){
    this.bar = someValue;
  },

  myMethodWhereEverythingHappens: function() {
    if(this.zar == this.bar) {
        //do something
    }
  },


}


Would that be correct? What’s the js pattern for dealing with that kind of OO considerations?

:slight_smile:

That’s one way of doing it. Scoping is a little less rigid in JS, a lot of it is by convention (e.g. prepend vars with an underscore to denote they’re private)

One of the other ways to do this would be to create a function object.

e.g. something along the lines of:


function Foo() {


    var that = this; //for scope resolution
    
    this._zar = '';
    this._bar = '';
    
    this.baz = ''
    
    this.setBar = function(val) {
        this._bar = val;
    }
    
    this.someMethod = function() {
        //do stuff
    }


}


var fooey = new Foo();

See: http://snipt.net/geekyjohn/basic-instantiable-object-example/