将对象的函数传递给其另一个函数

时间:2015-12-06 03:19:21

标签: javascript

这就是我所拥有的:

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");

doStuff函数可以与其他函数一起使用,但执行以下操作会返回undefined undefined

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

我拥有什么以及如何更改它以使其工作有什么问题? 感谢。

2 个答案:

答案 0 :(得分:4)

这是因为this没有引用该对象。

您可以使用.bind() method来设置this

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

但是,这不是很灵活,因此你可以在doStuff方法中绑定它:

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

答案 1 :(得分:2)

如果你知道foo.doStuff的arg总是希望在foo上调用,你可以在doStuff

中写下来
// ...
    doStuff: function (stuff) {
        return stuff.apply(this, Array.prototype.slice.call(arguments, 1));
    }
相关问题