JS in the call apply function and this usage

Source: Internet
Author: User

This introduction:

The meaning of this keyword in C # is relatively deterministic. JavaScript's this keyword, as the function of the use of different occasions, the value of this will change, feeling the usage is confusing, so it is necessary to tidy up the moment!

Summarize a principle: In JS, the this pointer represents the owner of the object executing the current code.

1. Pure function calls similar to C #:

function test () {  this.x = 1;  alert (x);} Test ();//1

Actually this is the global variable. The following example is a good way to understand that this is a global object.

var x = 1;function Test () {     alert (this.x);} Test ();//1var x = 1;function Test () {    this.x = 0;//Modified global variable, this is the Global object Global}test (); alert (x);//0

2, as a method call, then this refers to its parent object.

function test () {  alert (this.x);//this refers to its ancestor object, where the ancestor is the object that called the function P;}var p = {};p. x = 1;p.m = test;p.m (),//1; here m is the test method, P is this, the output is p.x;

3, as a constructor call: the so-called constructor, is to use new to generate a new object. At this point, this refers to this object.

function test () {   this.x = 1;} var p = new test (); alert (p.x);//1; This can also be understood as its ancestor object is a constructor p;

4, apply call this point is the first parameter in apply.

var x = 0;function Test () {   alert (this.x);} var p = {};//defines an object p.x = 1;p.m = Test;p.m.apply ();//0; When apply has no parameters, it is represented as a global object. So the value is var x = 0;p.m.apply (p);//1;p inherits Test, but this still points to its parent object p;

Call () and apply () two methods introduced:

Their role is to bind the function to another object to run, and the two differ only in the way that the parameter is defined:

Pager Method: Call (thisobj, [arg1,arg2 ...])
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.

Apply Method: Apply (thisobj, Argarray)
If Argarray is not a valid array or is not a arguments object, it will result in a TypeError. If none of the Argarray and Thisobj parameters are provided, then the Global object is used as a thisobj and cannot be passed any parameters.

The ECMAScript specification defines call () and apply () two methods for all functions, and the first parameter of call and apply is the function object that needs to be called, in the function body This parameter is the value of this , and the remaining parameter is the value that needs to be passed to the function. The difference is on the second parameter, after callexcept the first parameter is used to change the function of the this scope , followed by a few parameters, then the function has a few parameters, and apply a total of 2 parameters, the first parameter is the same as call, the second argument is an array, There are several values in it, then there are several parameters when executing the function, as in the following example:

var fun = function (param1,param2) {};

Fun.call (window,1,2);

Fun.apply (window,[1,2]);//The two are equivalent!

Now, let's see how they all work:

1. Differences with parameters and without parameters

function Main () {    var str = "Hello";    Console.log (str);} Main.call ();//hello; when call/apply has no arguments, it is represented as a global object. So the value is hello;

2. Use call to invoke the method in the prototype:

//1var arr1 = ["A1", "B2", "C3"];var value1 = Arr1.shift ();//shift removes the first element from the array and returns the value of the first element Console.log (value1); a1//notation 2var arr2 = ["A1", "B2", "C3"];var value2 = Array.prototype.shift.call (arr2);   A1; Call The shift method in the prototype prototype Console.log (value2);

Console.log is a print JS array and the function of the image, we use the most view JS output is alert, but alert can only play string or int,console.log can output the results in the browser console! Very good Debugging Tools!

3. Use call to imitate inheritance:

<Script>functionfun1 () { This. A= 123;  This. Add= function() {alert ( This. a);}}functionfun2 () { This. A= 456;}varF1=Newfun1 ()varF2=Newfun2 ()vara=F1.add.call (F2);//a output is 456, in the function body parameter F2 is the value of this, like F2 inheritance F1</Script>

Here is the method of F1 to F2 to use, F2 can use all the methods in F1, which is like the concept of inheritance in high-level languages (like F2 inheritance F1).

4. Use multiple call to implement multiple inheritance:

function fun1 () {    this.add = function () {return THIS.A}}function fun2 () {    this.sub = function () {return this. a-this.b}}function fun3 () {    this.a = ten;    this.b = 2;    Fun1.call (this);//this is the current object Fun3, which inherits Fun1 and Fun2    Fun2.call (this);//function is to Fun1 and Fun2 method "inherit" to Fun3} var f3 = new Fun3 () Alert (F3.add ()); Alert (F3.sub ());//So, who wants to inherit who can inherit

Here's how to use some arrays:

Array Object Method:

Concat ()

Concatenate two or more arrays and return the result

Join ()

Put all the elements of the array into a string. element is delimited by the specified delimiter (,)

Pop ()

Delete and return the last element of the array

Push ()

Adds one or more elements to the end of the array and returns the new length

Reverse ()

Reverses the order of elements in an array

Shift ()

Delete and return the first element of the array

Slice ()

Returns the selected element from an existing array slice (Start,end): Returns a new array containing elements from start to end (excluding the element) from the Arrayobject. Note that the method does not modify the array, but instead returns a subarray. If you want to delete an element in an array, you should use the method Array.splice ()

Sort ()

Sorting elements of an array

Splice ()

Delete the element and add a new element to the array: Array.splice (index,howmany,item1,....., ItemX)

Arr.splice (2,0, "William")

Index: Integer that specifies the position of the Add/delete item (starting at 0), using a negative number to specify the position from the end of the array.

Howmany: The number of items to be deleted, and if set to 0, item insertion, 1 substitution is not deleted.

Item1, ..., ItemX: optional, add a new item to the array.

ToString ()

Converts an array to a string and returns the result

Unshift ()

Arrayobject.unshift (Newelement1,newelement2,...., newelementx): Adds one or more elements to the beginning of the array and returns the new length

ValueOf ()

Returns the original value of an array object

JS in the call apply function and this usage

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.