JS Apply/call/caller/callee/bind using method and Difference analysis

Source: Internet
Author: User

The call method invokes one method of an object, replacing the current object with another object (in fact, changing the object's internal pointer, which changes the contents of the object's this point). JS code Call ([thisobj[,arg1[, arg2[, [,. ArgN]]]) parameter thisobj Optional. The object that will be used as the current object. Arg1, Arg2,, ArgN options available. The method parameter sequence will be passed. Indicates that the call method can be used to invoke a method in place of another object. The call method can change the object context of a function from the initial context to a new object specified by Thisobj. If the Thisobj parameter is not provided, then the Global object is used as the thisobj. The JS code copy Code code is as follows: Code function Obj () {this.value= "Object! ";} var value= "global variable"; function Fun1 () {alert (this.value);} window. Fun1 (); Global variable Fun1.call (window); Global variable Fun1.call (document.getElementById (' MyText ')); Input text Fun1.call (new OBJ ()); Object! JS Code Code Copy code is as follows: var first_object = {num:42}; var second_object = {num:24}; function Multiply (mult) {return this.num * mult;} multiply.call (First_object, 5); Returns * 5 Multiply.call (Second_object, 5); Returns 24 * 52, apply method The first parameter of the Apply method is also the object to pass to the current object, which is the this within the function. The arguments that follow are all arguments passed to the current object. Both apply and call are the same in effect, but they differ in parameters. For the first parameter, the meaning is the same, but for the second argument: Apply passes in an array of parameters, which is the combination of multiple parameters into an array, and call is passed in as a parameter of call (starting with the second argument). such as Func.call (FUNC1,VAR1,VAR2,VAR3) corresponding to the wording of apply: Func.apply (func1, [VAR1,VAR2,VAR3]) The benefit of using apply at the same time is that you can directly pass in the arguments object of the current function as the second parameter of apply. JS Code Copy Code is as follows: Var func=new function () {this.a= "func"} var myfunc=function (x, y) {var a= "myfunc"; alert (THIS.A); alert (x + y ); } myfunc.call (func, "var", "fun");//"Func" "var Fun" myfunc.apply (func,["var", "fun"]);//"Func" "var fun" three, the caller property returns a reference to a function that invokes the function body of the current function. The FunctionName.caller:functionName object is the name of the function being executed. Description: For a function, the caller property is defined only when the function executes. If the function is called by the top level of a JScript program, then caller contains null. If you use the Caller property in a string context, the result is the same as functionname.tostring, that is, the deserialized text of the function is displayed. The JS code copy Code code is as follows: function Calllevel () {if (Calllevel.caller = = null) alert ("Calllevel is called from the top level."); else Alert ("Calllevel is called by another function:\n" +calllevel.caller); } function Funcaller () {calllevel ();} Calllevel (); Funcaller () The Callee property returns the function object being executed, which is the body of the specified function object. [function.] Arguments.callee: The optional function parameter is the name of the function object that is currently executing. Description: The initial value of the Callee property is the Function object that is being executed. The Callee property is a member of the arguments object that represents a reference to the function object itself, which facilitates the recursion of an anonymous function or guarantees the encapsulation of a function, such as a recursive calculation of 1 to N of the sum of natural numbers from the bottom example. This property is available only if the related function is executing. It is also important to note that Callee has the length property, which is sometimes used for validation or better. Arguments.length is the length of the argument, and the arguments.callee.length is the length of the formal parameter, thus determining whether the parameter length is consistent with the argument length. The JS code copy Code code is as follows://callee can print its own function Calleedemo () {alert (Arguments.callee);}//For validating parameters function Calleelengthdemo (arg1, arg2) {if (arguments.length==arguments.callee.length) {window.alert ("Verify formal parameters and argument lengths are correct!") "); Return } else {alert ("argument length:" +arguments.length); alert ("Parameter length:" +arguments.callee.length);}} Recursive calculation var sum = function (n) {if (n <= 0) return 1; else return n +arguments.callee (n-1)} V, bind JS code copy Code code as follows: Var f Irst_object = {num:42}; var second_object = {num:24}; function Multiply (mult) {return this.num * mult;} Function.prototype.bind = function (obj) {var method = this, temp = function () {return method.apply (obj, arguments);}; r Eturn temp; } var first_multiply = Multiply.bind (First_object); First_multiply (5); Returns * 5 var second_multiply = Multiply.bind (Second_object); Second_multiply (5); Returns 24 * 56, JS Closure (Closure) The so-called "closure" refers to an expression (usually a function) that has many variables and environments that bind them, and so these variables are also part of the expression. The simplest description of closures is that ECMAScript allows the use of intrinsic functions-that is, function definitions and function expressions in the function body of another function. Furthermore, these intrinsic functions can access all local variables, arguments, and other intrinsics declared in the outer function in which they are located. When one of these intrinsics is called outside the outer function that contains them, a closure is formed. In other words, the intrinsic function returns in the outer functionAfter being executed. When this inner function executes, it still has to access local variables, arguments, and other intrinsic functions of its external function. The values of these local variables, parameters, and function declarations (initially) are the values that are returned by the external function, but are also affected by intrinsic functions. In short, the function of a closure is that after the out function is executed and returned, the closure makes the garbage collection mechanism of the JavaScript GC not reclaim the resources occupied by the out function, because the internal function of the out functions inner The execution of a function depends on the variables in the Out function. Two features of closures: 1, as a reference to a function variable-when the function returns, it is in the active state. 2, a closure is when a function returns, a stack that does not release resources. Example 1:html code Copy Code code is as follows:Build-setupsomeglobals () Output Value-galertnumber () Increase-gincreasenumber () Assignment 5-gsetnumber (5)Example 2:html code Copy Code code is as follows: Example 3:JS code copy Code code is as follows: Description: One of the key techniques is to create an additional execution environment by executing a single-line (in-line) function expression, and the intrinsic function returned by the function expression as a function used in external code. At this point, the buffered array is defined as a local variable of the function expression. This function expression is executed only once, and the array is created once and can be reused for functions that depend on it. VII. prototype chain ECMAScript defines an internal [[prototype]] property for the type Object. This property cannot be accessed directly through a script, but during property accessor parsing, you need to use the chain of objects referenced by this internal [[prototype]] Property-that is, the prototype chain. A common prototype property can be used to assign or define a prototype object corresponding to an internal [[prototype]] property. Example 1:JS code Copy Code code is as follows:
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.