开发者

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

How would I pass the testx function to the change_text function as a parameter?

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("HEL开发者_运维技巧LO, WORLD", 'theboxtochange', 'testx()');


By just giving its name (without parens or quotes):

var box = new change_text("HELLO, WORLD", 'theboxtochange', testx);

Functions are first-class objects, and so their names are references to them.

Within change_text, you would then call it by using your reference to it (func) like any other symbol pointing to a function, so:

func();


I have improved the code and now I understand that functions are first-class objects so any objects name is also a reference to it. and that name can be passed to other functions in the parameters by just ommiting the parenthesis around the name.

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

The last line of code calls the function that is passed to the first function.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜