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