Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a sibling method in an object defined with object syntax?

Tags:

javascript

How to do this?

var obj = {
 func1 : function(){
   // Do stuff 
 },
 func2 : function(){
  func1();  // does not work
  this.func1();  // does not work
 }
}

Edit: missed a semicolon

like image 781
SystemicPlural Avatar asked Feb 09 '11 16:02

SystemicPlural


3 Answers

var obj = {
 func1 : function(){
   // Do stuff 
 },
 func2 : function(){
  obj.func1();  // It works fine
 }
}
like image 163
Gustavo Costa De Oliveira Avatar answered Nov 06 '22 08:11

Gustavo Costa De Oliveira


if you want to use the 'this' keyword, you should do something like

function obj() {
    this.param = whatever;

}

obj.prototype.method1 = function(){
...
}

obj.prototype.method2 = function(){
    this.method1();
}

you could declare the methods in the obj function, but it is better to use prototype, because it is more efficient -- no matter how many obj instances you create, the functions only exist once. If you put the functions in the obj constructor, each instance of obj has its own copy of the function. javascript does some magic to associate the method call with the object instance on which it is called, to make sure 'this' means the right thing in context

like image 35
hvgotcodes Avatar answered Nov 06 '22 09:11

hvgotcodes


I don't know why the person asking the original question thought that wouldn't work. Their example does work.

var obj = {
 func1 : function(){
   console.log("doing stuff");
 },
 func2 : function(){
  this.func1();  // works fine!
 }
}

You can paste that into the console and call obj.func2() and it works just fine. You don't need to name the object in this situation.

But be careful. This solution wouldn't work if you define another anonymous function inside of func2, and then try to use "this" inside of that function (such as if you're defining a callback). You'll get a "Uncaught TypeError: this.func1 is not a function" error. The problem in that situation is that "this" no longer refers to the outer object, it now refers to the context of that new inner function. For example:

var obj = {
 func1 : function(){
   console.log("doing stuff");
 },
 func2 : function(){
   var func3 = function () {
     this.func1();  // doesn't work ("this" is no longer obj)
   }
   func3();
 }
}

To fix that issue, you could save a local copy of "this". Example:

var obj = {
 func1 : function(){
   console.log("doing stuff");
 },
 func2 : function(){
   var ourThis = this;
   var func3 = function () {
     ourThis.func1(); // works fine!
   }
   func3();
 }
}
like image 1
orrd Avatar answered Nov 06 '22 08:11

orrd