https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply

The apply() method calls a function with a given this value, and arguments provided as an array (or an array-like object).

Note: While the syntax of this function is almost identical to that of call(), the fundamental difference is that call() accepts an argument list, while apply() accepts a single array of arguments.

Syntax Section

function.apply(thisArg, [argsArray])

Parameters Section

thisArg
The value of this provided for the call to func. Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode code, null and undefined will be replaced with the global object, and primitive values will be boxed. This argument is not optional
argsArray
Optional. An array-like object, specifying the arguments with which func should be called, or null or undefined if no arguments should be provided to the function. Starting with ECMAScript 5 these arguments can be a generic array-like object instead of an array. See below for browser compatibility information.

Return value Section

The result of calling the function with the specified this value and arguments.

Description Section

You can assign a different this object when calling an existing function. this refers to the current object, the calling object. With apply, you can write a method once and then inherit it in another object, without having to rewrite the method for the new object.

apply is very similar to call(), except for the type of arguments it supports. You use an arguments array instead of a list of arguments (parameters). With apply, you can also use an array literal, for example, func.apply(this, ['eat', 'bananas']), or an Array object, for example, func.apply(this, new Array('eat', 'bananas')).

You can also use arguments for the argsArray parameter. arguments is a local variable of a function. It can be used for all unspecified arguments of the called object. Thus, you do not have to know the arguments of the called object when you use the apply method. You can use arguments to pass all the arguments to the called object. The called object is then responsible for handling the arguments.

Since ECMAScript 5th Edition you can also use any kind of object which is array-like, so in practice, this means it's going to have a property length and integer properties in the range (0..length-1). As an example you can now use a NodeList or a custom object like { 'length': 2, '0': 'eat', '1': 'bananas' }.

Most browsers, including Chrome 14 and Internet Explorer 9, still do not accept array-like objects and will throw an exception.

Examples Section

Using apply to append an array to another Section

We can use push to append an element to an array. And, because push accepts a variable number of arguments, we can also push multiple elements at once. But, if we pass an array to push, it will actually add that array as a single element, instead of adding the elements individually, so we end up with an array inside an array. What if that is not what we want? concat does have the behaviour we want in this case, but it does not actually append to the existing array but creates and returns a new array. But we wanted to append to our existing array... So what now? Write a loop? Surely not?

apply to the rescue!

var array = ['a', 'b'];
var elements = [0, 1, 2];
array.push.apply(array, elements);
console.info(array); // ["a", "b", 0, 1, 2]

https://www.w3schools.com/js/js_function_apply.asp

Method Reuse

With the apply() method, you can write a method that can be used on different objects.


The JavaScript apply() Method

The apply() method is similar to the call() method (previous chapter).

In this example the fullName method of person is applied on person1:

 var person = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
var person1 = {
firstName: "Mary",
lastName: "Doe"
}
person.fullName.apply(person1); // Will return "Mary Doe"

The Difference Between call() and apply()

The difference is:

The call() method takes arguments separately.

The apply() method takes arguments as an array.

The apply() method is very handy if you want to use an array instead of an argument list.

The apply() Method with Arguments

The apply() method accepts arguments in an array:

var person = {
fullName: function(city, country) {
return this.firstName + " " + this.lastName + "," + city + "," + country;
}
}
var person1 = {
firstName:"John",
lastName: "Doe"
}
person.fullName.apply(person1, ["Oslo", "Norway"]); //这里是一个array参数

Compared with the call() method:

var person = {
fullName: function(city, country) {
return this.firstName + " " + this.lastName + "," + city + "," + country;
}
}
var person1 = {
firstName:"John",
lastName: "Doe"
}
person.fullName.call(person1, "Oslo", "Norway"); //这里是2个参数

JavaScript apply的更多相关文章

  1. JavaScript apply函数小案例

    //回调函数1 function callback(a,b,c) { alert(a+b+c); } //回调函数2 function callback2(a,b) { alert(a+b); } / ...

  2. javascript:apply方法 以及和call的区别 (转载)

    javascript:apply方法   1.        apply和call的区别在哪里 2.        什么情况下用apply,什么情况下用call 3.        apply的其他巧 ...

  3. 深入学习JavaScript: apply 方法 详解(转)——非常好

    主要我是要解决一下几个问题: 1.        apply和call的区别在哪里 2.        什么情况下用apply,什么情况下用call 3.        apply的其他巧妙用法(一般 ...

  4. [每天解决一问题系列 - 0001] Javascript apply和 call对比

    相同点: 每个函数都包含这两个原生的方法 他们两个的效果是一样的,用于在特定的作用域下执行函数,本质上是设置函数内this对象的值. 不同点: 传入的参数类型不同 . apply(函数作用域,arra ...

  5. javascript:apply方法

    1.        apply和call的区别在哪里 2.        什么情况下用apply,什么情况下用call 3.        apply的其他巧妙用法(一般在什么情况下可以使用apply ...

  6. JavaScript: apply 方法 详解(转)——非常好

    转载自  http://www.cnblogs.com/KeenLeung/archive/2012/11/19/2778229.html 我在一开始看到javascript的函数apply和call ...

  7. 深入学习JavaScript: apply 方法 详解

    我在一开始看到javascript的函数apply和call时,非常的模糊,看也看不懂,最近在网上看到一些文章对apply方法和call的一些示例,总算是看的有点眉目了,在这里我做如下笔记,希望和大家 ...

  8. JavaScript: apply , call 方法

    我在一开始看到javascript的函数apply和call时,非常的模糊,看也看不懂,最近在网上看到一些文章对apply方法和call的一些示例,总算是看的有点眉目了,在这里我做如下笔记,希望和大家 ...

  9. JavaScript apply使用

    call 和 apply 作用: 都是为了改变某个函数运行的context上下文而存在的,为了改变函数体内部 this的指向 JavaScript函数存在定义时上下文和运行时上下文, 上下文(cont ...

随机推荐

  1. 洛谷 - P3469 - BLO-Blockade - 割点

    https://www.luogu.org/problem/P3469 翻译:一个原本连通的无向图,可以删除图中的一个点,求因为删除这个点所导致的不连通的有序点对的数量.或者说,删去这个点之后,各个连 ...

  2. 3种Redis分布式锁的对比

    我们通常使用的synchronized或者Lock都是线程锁,对同一个JVM进程内的多个线程有效.因为锁的本质 是内存中存放一个标记,记录获取锁的线程是谁,这个标记对每个线程都可见.然而我们启动的多个 ...

  3. 现身说法:面对DDoS攻击时该如何防御?

    上周,我们的网站遭到了一次DDoS攻击.虽然我对DDoS的防御还是比较了解,但是真正遇到时依然打了我个措手不及.DDoS防御是一件比较繁琐的事,面对各种不同类型的攻击,防御方式也不尽相同.对于攻击来的 ...

  4. 三、Signalr外部链接

    一.本地外部引用 <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head& ...

  5. iptable防火墙原理

    iptable防火墙原理 简介 Linux 2.0 ipfs/firewalld Linux 2.2 ipchain/firewall Linux 2.4 iptables/netfilter (ip ...

  6. 前端matrix矩阵的变化

    css3 transform中的matrix矩阵   CSS3中的矩阵CSS3中的矩阵指的是一个方法,书写为matrix()和matrix3d(),前者是元素2D平面的移动变换(transform), ...

  7. java课堂动手测试2

    测试一 编写一个方法,使用以上算法生成指定数目(比如1000个)的随机整数. 程序源代码 import java.util.Random;import java.util.Scanner; publi ...

  8. 一些项目中用到的php函数

    #不为空 if (!empty($_POST)) { } #生成随机数 mt_rand(,)产生999-9999范围间的随机数

  9. day_14 匿名函数与内置函数连用 作业题

    ''' 要求: 从文件中取出每一条记录放入列表中,列表的每个元素都是` {'name':'egon','sex':'male','age':18,'salary':3000}`的形式 ''' all_ ...

  10. WIN 7 的vs2008 试用版评估期结束的解决方法

    1. 在VS2008安装目录下把Setup/setup.sdb文件中的 [Product Key] T2CRQGDKBVW7KJR8C6CKXMW3D 改成 [Product Key] PYHYPWX ...