如何在第一个函数参数中将一个函数传递给另一个函数

How would I pass one function to another function in the first functions parameters?

本文关键字:函数 一个 另一个 第一个 参数      更新时间:2023-09-26

如何将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()');

只需给出它的名称(不带括号或引号):

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

最后一行代码调用传递给第一个函数的函数。