Javascript |将对象函数作为参数传递给另一个对象

时间:2017-07-15 00:04:36

标签: javascript object methods p5.js

我目前正在使用javascript构建GUI,我希望能够将一个对象函数作为参数传递给另一个对象,下面的代码演示了问题和预期的输出。

var Window = function(){
    this.close = function(){
        console.log(this)
    }
}


var Button = function(func){
    this.func = func;
    this.press = function(){
        this.func();
    }
}

var win = new Window();
var button = new Button(win.close);

button.press();
//Output: Button object
//Expected output: Window object

5 个答案:

答案 0 :(得分:3)

您应该将函数绑定到您想要引用的对象this。查看此MDN参考,了解如何使用Function#bind

var Window = function(){
    
    this.close = function(){
        console.log(this)
    }
    this.close = this.close.bind(this)
}


var Button = function(func){
    this.func = func;
    this.press = function(){
        this.func();
    }
}

var win = new Window();
var button = new Button(win.close);

button.press();

答案 1 :(得分:1)

var Button = function(func){
    //this.func = func; this is not required.
    this.press = function(){
       func(); //just call func
    }
}

答案 2 :(得分:0)

var Window = function(){
    var w = {};
    w.close = function(){
        console.log(w);
    }
    return w;
}


var Button = function(func){
    var b = {press: func};
    return b;
}

var win = new Window();
var button = new Button(win.close);

button.press();

答案 3 :(得分:0)

您可以保留这样的参考:

var Window = function(){
    var context= this;
    this.close = function(){
        console.log(context)
        //output: Object { close: Window/this.close() }
    }
}


var Button = function(func){
    this.func = func;
    this.press = function(){
        this.func();
    }
}

var win = new Window();
var button = new Button(win.close);

button.press();

答案 4 :(得分:0)

你需要传递外部'this'作为一个不同的变量传递给press(),如下所示。我将'this'分配给'self',我在press()中引用了它。这是我对您的代码所做的唯一更改。

var Window = function(){
  this.close = function(){
    console.log(this)
  }
}


var Button = function(func){
   let self = this;      // this is the change I made
   this.func = func;
   this.press = function(){
     self.func();        // this is the change I made
  }
}

var win = new Window();
var button = new Button(win.close);

button.press();
相关问题