【问题标题】:Difference between passing arguments VS apply with arguments传递参数与应用参数之间的区别
【发布时间】:2016-04-19 16:28:56
【问题描述】:

我有一个骨干集合,它使用保存混合来进行批量保存(只是一种实用方法,因为骨干本身不支持批量保存)

// 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); 
                }
            });
        }
    };
});

所以当我想批量保存集合时,我会调用

cars.save();

我在这里遇到的问题是在ajax 方法的success 回调中,我将调用选项对象中可用的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

谁能解释这两种情况的区别?

【问题讨论】:

    标签: javascript ajax function backbone.js apply


    【解决方案1】:

    在第一个示例中,您只需将参数对象传递给该函数。

    在第二个中,您使用apply 调用该函数。简而言之,apply 函数使用“扩展”参数调用该函数。这意味着您的函数被称为 yourFunction(arg0 /* 其中 arg 是来自参数 */, arg1, argN, ...) 的单个元素,并带有给定的“this”。有关更多信息,请参阅我指出的页面。

    【讨论】:

    • 你的意思是说,如果我的函数有 3 个参数,那么 apply 将按如下方式工作 onSuccess: function(cars, successString, xhr) { } 我可以在哪里访问方法中的每个参数?
    • 是的,确实如此。您将获得 3 个参数,您可以像调用 option.onSuccess(car, successString, xhr) 一样轻松访问它们。
    • 这是有道理的。感谢您清除我的疑问:)
    猜你喜欢
    • 2020-02-06
    • 2021-12-07
    • 2014-02-06
    • 2014-06-08
    • 2013-10-21
    • 1970-01-01
    • 1970-01-01
    • 2011-08-19
    • 2015-07-18
    相关资源
    最近更新 更多