.apply到底是做什么的? [英] What exactly does .apply do?

查看:176
本文介绍了.apply到底是做什么的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以前从未见过.apply方法.有人可以向我解释它的作用吗?这取自 http://addyosmani.github.com/backbone-fundamentals/

Never seen the .apply method before. Can someone explains to me what it does? This is taken from http://addyosmani.github.com/backbone-fundamentals/

var app = app || {}; 
var TodoList = Backbone.Collection.extend({
model: app.Todo,
localStorage: new Backbone.LocalStorage(’todos-backbone’),
completed: function() {
    return this.filter(function( todo ) {
        return todo.get(’completed’); 
    });
},
remaining: function() {
    return this.without.apply( this, this.completed() );
}, 
nextOrder: function() {
    if ( !this.length ) { 
        return 1;
    }
    return this.last().get(’order’) + 1; },
comparator: function( todo ) { 
    return todo.get(’order’);
} 
});
app.Todos = new TodoList();

推荐答案

该函数对象带有apply()call()方法.他们都有效地做相同的事情,只是略有不同.它们的作用是允许您在该函数的作用域内定义this指针.例如,如果您这样做:

The function object comes with apply() and call() methods. They both effectively do the same thing, except slightly differently. What they do is allow you to define the this pointer inside of that function's scope. So for example, if you do:

function myFunc(param1, param2) { alert(this) }

var first = 'foo';
var second = 'bar';

myFunc.call('test', first, second); //alerts 'test'

myFunc.apply('test', [first, second]); //alerts 'test'

在两种方法中,都将this指针作为第一个参数传递.在call()方法中,此后按顺序传递所有后续参数,以使第二个参数成为myFunc的第一个参数.在apply()方法中,您将额外的参数作为数组传递.

In both methods, you pass the this pointer as the first parameter. In the call() method, you pass all subsequent parameters in sequential order after that, such that the second argument becomes the first parameter of myFunc. In the apply() method, you pass the extra parameters in as an array.

这篇关于.apply到底是做什么的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆