0

what's best practice when it comes to keeping track of an object reference in javascript:

function class1(param) {
this.param = param;
self = this;
}

class1.prototype.method1 = function () {
console.log(self.param);
}

$('document').ready(function () {
   object1 = new class1('foo');
   object2 = new class1('bar');
   object1.method1(); // expected: foo , actual: bar 
   })

http://jsfiddle.net/d7q5f/

Currently self appears to be global and is overridden in the constructor of object2. I'd be very grateful if someone could offer some advice.

Alex Char
  • 32,879
  • 9
  • 49
  • 70
  • You probably only need a reference to `this` when you're going to pass a function member as a callback or event handler. In that case it's better to pass a bound function or a closure as explained here: http://stackoverflow.com/a/16063711/1641941 under `the this variable` Then use `var self = this` and make sure it's in the same scope as self is now within constructor scope so anything outside the constructor can't access it. – HMR Jul 11 '14 at 11:42

2 Answers2

1

You don't need to keep track, just use this like so:

function class1(param) {
this.param = param;
}

class1.prototype.method1 = function () {
console.log(this.param);
}
Poelinca Dorin
  • 9,577
  • 2
  • 39
  • 43
1
function class1(param) {
    this.param = param;
}

class1.prototype.method1 = function () {
    console.log(this.param);
}

$('document').ready(function () {
   var object1 = new class1('foo');
   var object2 = new class1('bar');
   object1.method1(); // expected: foo , actual: foo 
});

Why you want to add this self thing?

jsfiddle

jasonslyvia
  • 2,529
  • 1
  • 24
  • 33