【发布时间】:2017-12-20 03:44:23
【问题描述】:
我目前正在用 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
【问题讨论】:
-
您应该将 win.close 绑定到窗口。这意味着这样做:
win.close.bind(win)。 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… -
也可以使用箭头函数
var button = new Button(() => win.close());
标签: javascript object methods p5.js