0

Given an object like this:

var MyObj = {
  bar: 10,
  foo: function() {
     alert(MyObj.bar);
  }
}

How can I generically reference MyObj from MyObj.foo such that if I were to change var MyObj to var MyObj2 I wouldn't need to modify the foo function?

user126715
  • 3,648
  • 3
  • 23
  • 25

2 Answers2

1

If you want to treat MyObj like a class, you could do something like what lumio suggested, or you could do something like

function MyObj(){
    this.bar = 10;
    this.foo = function(){ 
        return this.bar; 
    }
}
var a = new MyObj();
var b = new MyObj();
b.bar = 5;
console.log(a.foo(), b.foo()) // 10 5

If instead, you just want to reference the object's bar value, then you could just replace the alert(MyObj.bar); with alert(this.bar);

Garrett
  • 106
  • 5
  • Thank you, this looks like what I need. I'm not really trying to do real "class" logic -- just want to namespace some helper functions more or less. If I have nested structures (`MyObj.foo.bar.baz.func1();`), I'm thinking I can do `var that = this;` right at the top of the function and then `that` will always reference parent no matter where I am – user126715 Oct 10 '17 at 19:36
0

Classes would help you a lot here. In ES5 classes can be created like so:

function MyObj() {
  this.bar = 10;
}
MyObj.prototype.foo = function() {
  console.log( this.bar );
}

var objInstance = new MyObj;
objInstance.foo();

var objInstance2 = new MyObj;
objInstance2.bar = 20;
objInstance2.foo();

ES6 allows an even better notation:

class MyObj {
  constructor() {
    this.bar = 10;
  }
  
  foo() {
    console.log( this.bar );
  }
}

var objInstance = new MyObj;
objInstance.foo();

var objInstance2 = new MyObj;
objInstance2.bar = 20;
objInstance2.foo();

Use babel to convert it to ES5.

lumio
  • 7,428
  • 4
  • 40
  • 56