0

I'm trying to implement some basic object orientation in javascript like so:

function Cat(name) {
  this.name = name;
}

Cat.prototype.sayName = function() {
  console.log(this.name);
};

Cat.prototype.fetchCat = function() {
  someAsyncCall()
      .success(this.sayName)
      .error(someOtherMethod);
};

when someAsyncCall is finished sayName gets called but the this scope is not what I expect. I can solve it by binding:

Cat.prototype.fetchCat = function() {
  someAsyncCall()
      .success(this.sayName.bind(this))
      .error(someOtherMethod.bind(this));
};

Is there some syntactically "nicer" solution to this than having to remember to .bind all the time when in callbacks?

Cotten
  • 7,859
  • 17
  • 54
  • 90
  • Maybe not the best solution, but I usually use a local variable `var self = this;` in the function so that `self` can be used in the callbacks to be sure the correct `this` is being used. – jonhopkins Dec 02 '13 at 13:26

2 Answers2

1
Cat.prototype.fetchCat = function() {
var self = this;
  someAsyncCall()
      .success(function(){self.sayName})
      .error(someOtherMethod);
};
Flavien Volken
  • 14,820
  • 9
  • 78
  • 105
  • I think you need `.success(function(){self.sayName();})` or it'll be the same as passing this.sayname – HMR Dec 02 '13 at 13:56
  • Actually both will be working, **but** using mine assume we are using `self` everywhere in the other functions instead of `this`, yours will allow using `this` in the right context which is actually better. I updated my answer. – Flavien Volken Dec 02 '13 at 14:43
-2

With reference to javascript guide lines from airbnb,

// bad
function() {
  var self = this;
  return function() {
    console.log(self);
  };
}

// bad
function() {
  var that = this;
  return function() {
    console.log(that);
  };
}

// good
function() {
  var _this = this;
  return function() {
    console.log(_this);
  };
}

ecma-262 does not give any special treatment for underscore and says:

The dollar sign ($) and the underscore (_) are permitted anywhere in an IdentifierName.

but since javascript as a language does not support encapsulation out of the box, the '_' convention is meant to indicate that the variable is 'private' or shouldn't be used externally.

MIdhun Krishna
  • 1,601
  • 11
  • 28
  • Possible reason here: [link](http://stackoverflow.com/questions/4484424/underscore-prefix-for-property-and-method-names-in-javascript), still I strongly prefer "self" – Flavien Volken Dec 02 '13 at 13:33