抱歉,如果这很简单,但我无法让它工作,即使我已经阅读了许多类似的主题几个小时。我不知道还要搜索什么。
我想调用一个回调函数,但是是对象内的回调函数,而不仅仅是全局(?)范围内的函数。
var something = function (x) {
this.x = x;
};
something.prototype.alertx = function() {
alert(this.x);
};
something.prototype.logx = function() {
console.log(this.x);
};
something.prototype.multiplyxby2 = function(callback){
this.x *= 2;
callback.call(this); // this is where I am stuck!!
// obviously this.callback(); doesn't work either.
};
var foo = new something(20);
foo.multiplyxby2('logx');
// or
foo.multiplyxby2('alertx');
谢谢
最佳答案
如果您尝试将方法名称作为字符串传递,则可以使用 [methodname]
语法来引用它,例如 this[methodname]();
它位于您的代码块中:
var something = function (x) {
this.x = x;
};
something.prototype.alertx = function() {
alert(this.x);
};
something.prototype.logx = function() {
console.log(this.x);
};
something.prototype.multiplyxby2 = function(method){
this.x *= 2;
// execute the passed in method
this[method]();
};
var foo = new something(20);
foo.multiplyxby2('logx');
// or
foo.multiplyxby2('alertx');
关于javascript - 原型(prototype)回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31508259/