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.
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. Check this MDN reference for how to use 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. I assigned 'this' to 'self' and I referenced it in the 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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.