我正在尝试扩展一些现有功能,使其具有一个回调函数,该函数将原始对象作为参数传递,或者至少传递存储在较小对象中的任何公共(public)变量,我该如何实现这一点?
这是我正在使用的文件的简化版本,一个类将包含在变量中
<html>
<head>
</head>
<script>
var foo = new Foo ({
arg1:1,
onComplete: function(){
alert("complete " + total);
}
});
</script>
<body>
</body>
</html>
函数/类看起来与此类似
function Foo(options) {
// private
var number1_ = options.arg1;
var number2_ = 10;
var total_ = number1_ + number2_;
// public
this.total = total_;
(function Foo() {
if (options) {
if (options.onComplete && typeof (options.onComplete) === "function") {
// how do I pass Foo or an object of selected variables here?
options.onComplete();
}
}
})();
}
谢谢
最佳答案
看看这个:)
function Foo(options) {
// private
var number1_ = options.arg1,
number2_ = 10,
total_ = number1_ + number2_;
// public
this.total = total_;
(function Magazine( that ) {
(options.onComplete || function(){}).call( that );
})(this);
}
var foo = new Foo({
arg1: 1,
onComplete: function() {
alert("complete " + this.total);
}
});
关于带有回调的 Javascript 函数,该回调将启动的对象作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8656363/