[英]How would I pass one function to another function in the first functions parameters?
我如何將testx函數作為參數傳遞給change_text函數?
function change_text(to, id, func) {
this.to = to;
this.id = id;
this.doit = function() {
this.target = document.getElementById(this.id);
this.target.innerHTML = this.to;
}
func;
}
function testx() {
alert("TESTING");
}
var box = new change_text("HELLO, WORLD", 'theboxtochange', 'testx()');
通過給它的名字(沒有parens或引號):
var box = new change_text("HELLO, WORLD", 'theboxtochange', testx);
函數是第一類對象,因此它們的名稱是對它們的引用。
在change_text
,您可以通過使用對它的引用( func
)來調用它,就像指向函數的任何其他符號一樣,所以:
func();
我已經改進了代碼,現在我明白函數是第一類對象,所以任何對象名稱也是對它的引用。 並且只需省略名稱旁邊的括號即可將該名稱傳遞給參數中的其他函數。
function change_text(to, id, func) {
this.to = to;
this.id = id;
this.doit = function() {
this.target = document.getElementById(this.id);
this.target.innerHTML = this.to;
}
this.func = func;
}
function testx() {
alert("TESTING");
}
var box = new change_text("HELLO, WORLD", 'theboxtochange', testx());
box.func()
最后一行代碼調用傳遞給第一個函數的函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.