开发者

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

How to do this?

var obj = {
 func1 : function(){
   // Do stuff 
 },
 func2 : function(){
  func1();  // do开发者_如何学Pythones not work
  this.func1();  // does not work
 }
}

Edit: missed a semicolon


var obj = {
 func1 : function(){
   // Do stuff 
 },
 func2 : function(){
  obj.func1();  // It works fine
 }
}


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


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();
 }
}


Another way is to create your object through a factory function. That way, you can initialize your functions and use them inside the others.

const objFactory = () => {
  const func1 = () => {
    // Do stuff
  }

  const func2 = () => {
    func1(); // This will work
  }

  return { func1, func2 }
}

const obj = objFactory();
obj.func1();
obj.func2();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜