[英]Javascript | Pass an objects function as argument into another object
我目前正在用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
你應該綁定的功能,你想要的對象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();
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();
您可以保留這樣的參考:
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();
您需要將外部“ 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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.