How to transfer one function to another function in the first parameters of functions?

How to pass testx function to 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("HELLO, WORLD", 'theboxtochange', 'testx()');
+3
source share
2 answers

Just indicating your name (without parsers or quotes):

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

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

Inside, change_textyou then call it using your reference to it ( func), like any other character pointing to a function, therefore:

func();
+5
source

I improved the code, and now I understand that functions are first-class objects, so any object name is also a reference to it. and this name can be passed to other functions in the parameters by simply dropping the brackets 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()

, .

0

All Articles