Passing an object function to another function

This is what I have:

var Person = function(fname, lname) {
        this.fname = fname;
        this.lname = lname;
    };

    Person.prototype = {
        getFullName: function() {
            return this.fname + " " + this.lname;
        },
        doStuff: function(stuff) {
            return stuff();
        }
    };

var john = new Person("John", "Doe");

The function doStuffworks with other functions, but makes the following returns undefined undefined:

console.log(john.doStuff(john.getFullName));

What happened to what I have, and how can I change it to make it work? Thanks.

+4
source share
2 answers

This is because it thisdoes not refer to an object.

You can use the method .bind()to set the value this:

john.doStuff(john.getFullName.bind(john));

However, this is not very flexible, so you can just bind it to a method doStuff:

doStuff: function(stuff) {
  return stuff.apply(this);
}
+4
source

If you know foo.doStuffarg always wants to be called on foo, you can write it indoStuff

// ...
    doStuff: function (stuff) {
        return stuff.apply(this, Array.prototype.slice.call(arguments, 1));
    }
+2
source

Source: https://habr.com/ru/post/1618754/


All Articles