2015-07-20 36 views
0

对不起,如果这很简单,但我不能得到它的工作,即使我已经阅读了许多类似的话题几个小时。我不知道还有什么要搜索的。原型回调

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

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

感谢

回答

1

在你的情况要传递的功能,被称为一个字符串,所以你需要去执行的函数引用。由于函数是this对象的成员,则可以使用括号标记下面给出得到函数参照,然后调用它

var something = function(x) { 
 
    this.x = x; 
 
}; 
 

 
something.prototype.alertx = function() { 
 
    snippet.log('alertx:' + this.x); 
 
}; 
 

 
something.prototype.logx = function() { 
 
    snippet.log('logx:' + this.x); 
 
}; 
 

 
something.prototype.multiplyxby2 = function(callback) { 
 
    this.x *= 2; 
 
    this[callback](); 
 
}; 
 

 
var foo = new something(20); 
 
foo.multiplyxby2('alertx'); 
 
foo.multiplyxby2('logx');
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> 
 
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>


另一种选择是通过直接函数引用作为回调等

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(foo.alertx); 
foo.multiplyxby2(foo.logx); 
  1. 列表项
+0

谢谢你,先生!! '这个[callback] .call(this);'和'this。[callback]()'在jfriend00的答案中有什么区别?只要将上下文传递给回调函数? –

+0

@BenA。有没有....我也已经更新了答案....因为我们使用的是正确的上下文调用回调没有必要使用'.CALL()' –

+0

谢谢!很有帮助。 –

2

如果你想传递一个方法名字作为一个字符串,那么你可以使用[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'); 
+0

谢谢我的朋友! –