Sai*_*Sai 1 javascript parameters callback javascript-events
我有一个自定义对象,它实现了一个稍后会执行的函数.以下是有人称之为:
customObject.onSomething(function(e) {
// do something with e
console.log('foobar');
});
Run Code Online (Sandbox Code Playgroud)
以下是onSomething的创建方式:
var CustomObject = function() {
this.onSomething = function(callback) {
// If the user passes in parameter(s), how can I modify them before calling?
callback.apply(this);
}
}
Run Code Online (Sandbox Code Playgroud)
在执行应用或调用函数之前,如何修改用户传入的参数?
apply获取第二个参数,该参数是要传递给函数的参数列表.call做同样的事情,除了它传递自己的参数列表(在第一个参数之后的所有东西this).
因此,如果你知道你期望哪些参数,你可以将它们作为第二个参数apply(或作为参数列表call)添加到调用函数中:
this.onSomething = function(arg1, arg2) {
// reverse the first and second arguments
callback.apply(this, [arg2, arg1]);
// equivalent:
callback.call(this, arg2, arg1);
};
Run Code Online (Sandbox Code Playgroud)
如果你不知道期望什么样的参数,但你仍然想对它们做些什么,你可以使用内置的arguments伪数组来保存给当前函数的参数(即使你没有声明)他们明确地).
您可以使用它来调用带有调用函数的相同参数的回调,或者对它们进行一些转换; 例如:
this.onSomething = function() {
// call callback with the same arguments we got
callback.apply(this, arguments);
// or, make some changes
var newArgs = ["extra argument", arguments[1], arguments[0]];
callback.apply(this, newArgs);
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2525 次 |
| 最近记录: |