简体   繁体   English

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

[英]Javascript | Pass an objects function as argument into another object

I'm currently building a GUI in javascript, and I want to be able to pass one objects function as an argument to another object, the code below demonstrates the problem and the expected output. 我目前正在用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

You should bind the function to the object you want this to reference. 你应该绑定的功能,你想要的对象this引用。 Check this MDN reference for how to use Function#bind 检查此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(); 

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

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

You can keep a reference like this: 您可以保留这样的参考:

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

you need to pass outer 'this' to be passed to press() as a different variable like I shown in below. 您需要将外部“ this”作为另一个变量传递给press(),如下所示。 I assigned 'this' to 'self' and I referenced it in the press(). 我将“ this”分配给“ self”,并在press()中引用了它。 That is the only change I made to your code. 这是我对您的代码所做的唯一更改。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM