JavaScript Apply Usage

Source: Internet
Author: User

Funobj.apply ([Thisobj[,argarray]])


Applies a method of an object, replacing the current object with another object.

When the Functionobj method executes, the This object in the function is replaced by the thisobj.

Thisobj can be selected. The object that will be used as the current object.

Argarray can be selected. An array of arguments to be passed to the function.

Apply in the application of object inheritance, do not use prototype, implicitly assigns the parent object attribute to the child object

The code is as follows Copy Code

Function par (name)
{
This.parname=name;
}
function Child (Chname,parname) {
This.chname=chname;
Par.apply (this,new Array (parname));
};

var o=new child ("John", "Mr John");
Alert (o.parname+ ";") +o.chname);

Apply can be used in common method invocation
Window.onunload=function ()
{
Alert ("Unload event is fired!");
}

function Saybye (name,toname)
{
Alert (name+ "says bye to" +toname);
}
function Sayendbiz (name,toname,content)
{
Alert (name+ "ends his talk about" +content + "with" +toname);
}

function AddTo (args,func)
{
var oldhandler=window.onunload| | function () {};
Window.onunload=function ()
{
Func.apply (Window,args);
oldhandler.apply (window, args);
}
}
AddTo (New Array ("John", "everyone"), Saybye);
AddTo (New Array ("John", "Everyone", "deveopment strategy of the Company"), Sayendbiz)

Other

Both apply and call are the same in effect, but they differ in their parameters.
Is the same for the first parameter, but for the second argument:
Apply passes in an array of arguments, which is the combination of multiple arguments into an array, while call is passed as a call parameter (starting with the second argument).
such as Func.call (FUNC1,VAR1,VAR2,VAR3) corresponding apply is written as: Func.apply (FUNC1,[VAR1,VAR2,VAR3))

The advantage of using apply at the same time is that you can simply pass the arguments object of the current function as the second argument to apply

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.