传递参数与应用参数之间的区别
Difference between passing arguments VS apply with arguments
我有一个 backbone collection,它使用保存混合来进行批量保存(只是一种实用方法,因为 backbone 本身不支持批量保存)
// Cars collection
define([
'Car',
'BulkSave'
], function(Car, BulkSave) {
return Backbone.Collection.extend({
model: Car,
save: function() {
var options = {
...
onSuccess: function(cars) {
// do something with cars
console.log(cars);
}
...
};
this.bulkSave(options);
}
}).mixin(BulkSave);
});
// BulkSave Mixin definition
define([], function(){
return {
save: function(options){
var thisCollection = this;
$.ajax({
type: options.type,
url: options.url,
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(options.data),
success: function(data) {
// data would give me the list of cars
// that changed
options.onSuccess.apply(thisCollection, arguments);
}
});
}
};
});
所以当我想批量保存 collection 时,我会调用
cars.save();
我在这里遇到的问题是在 ajax
方法的 success
回调中,我将调用选项 object 中可用的 onSuccess
方法我将传递参数。
和
有什么区别
options.onSuccess(arguments);
// this logs an arrayList of 3 properties
// [0] -- the actual list of cars which changed
// [1] -- 'success'
// [2] -- the xhr object
对
options.onSuccess(thisCollection, arguments);
// When i do this instead
// it logs
// the list of cars that changed instead
有人可以解释这两种情况之间的区别吗?
在第一个示例中,您只需将参数对象传递给该函数。
在第二个中,您使用 apply 调用函数。简而言之,apply 函数使用 "spread" 个参数调用函数。这意味着你的函数被称为 yourFunction(arg0 /* where arg is a single element from arguments */, arg1, argN, ...) 给定 "this"。有关更多信息,请参阅我指出的页面。
我有一个 backbone collection,它使用保存混合来进行批量保存(只是一种实用方法,因为 backbone 本身不支持批量保存)
// Cars collection
define([
'Car',
'BulkSave'
], function(Car, BulkSave) {
return Backbone.Collection.extend({
model: Car,
save: function() {
var options = {
...
onSuccess: function(cars) {
// do something with cars
console.log(cars);
}
...
};
this.bulkSave(options);
}
}).mixin(BulkSave);
});
// BulkSave Mixin definition
define([], function(){
return {
save: function(options){
var thisCollection = this;
$.ajax({
type: options.type,
url: options.url,
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(options.data),
success: function(data) {
// data would give me the list of cars
// that changed
options.onSuccess.apply(thisCollection, arguments);
}
});
}
};
});
所以当我想批量保存 collection 时,我会调用
cars.save();
我在这里遇到的问题是在 ajax
方法的 success
回调中,我将调用选项 object 中可用的 onSuccess
方法我将传递参数。
和
有什么区别options.onSuccess(arguments);
// this logs an arrayList of 3 properties
// [0] -- the actual list of cars which changed
// [1] -- 'success'
// [2] -- the xhr object
对
options.onSuccess(thisCollection, arguments);
// When i do this instead
// it logs
// the list of cars that changed instead
有人可以解释这两种情况之间的区别吗?
在第一个示例中,您只需将参数对象传递给该函数。
在第二个中,您使用 apply 调用函数。简而言之,apply 函数使用 "spread" 个参数调用函数。这意味着你的函数被称为 yourFunction(arg0 /* where arg is a single element from arguments */, arg1, argN, ...) 给定 "this"。有关更多信息,请参阅我指出的页面。