这是我的:
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));
我所拥有的东西有什么问题,我该如何改变它才能让它发挥作用? 谢谢。
最佳答案
这是因为 this
没有引用对象。
您可以使用 .bind()
method为了设置 this
的值:
john.doStuff(john.getFullName.bind(john));
但是,这不是很灵活,因此您可以将它绑定(bind)在 doStuff
方法中:
doStuff: function(stuff) {
return stuff.apply(this);
}
关于javascript - 将一个对象的函数传递给它的另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34113624/