javascript - 原型(prototype)回调

标签 javascript

抱歉,如果这很简单,但我无法让它工作,即使我已经阅读了许多类似的主题几个小时。我不知道还要搜索什么。

我想调用一个回调函数,但是是对象内的回调函数,而不仅仅是全局(?)范围内的函数。

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/

相关文章:

javascript - 如何从 jQuery 对象获取特定的 html

javascript - 扩展 Google map 范围,使 div 叠加层不覆盖任何标记

javascript - ie8 javascript 未运行或加载

javascript - 导入多个集合(nodejs、mongodb)

Javascript JSON.stringify 返回 []

javascript - AJAX 聊天提交仅适用于 $(document).keypress()

javascript - TinyMCE 为每个文本区域加载 content.min.css

javascript - IE 9 及以下版本在显示滑出侧边栏菜单时出现问题

javascript - 实现可折叠: how to determine which section is open?

javascript - 获取特定 View 的项目计数