Chat: Four invocation patterns of functions in JavaScript

Source: Internet
Author: User

in JS, whether it is a function, or a method, or an event, or a constructor, ... Its essence is all functions. It's just a different seat.

Four modes are: function mode, method mode, constructor mode, context mode

1. Function mode

Feature: is a simple function call. There is no boot content in front of the function name, where this represents the global object, which is window in the browser.

Like what:

function foo () {}

var func = function () {};

...

Foo ();

Func ();

(function () {}) ();

2. Method mode

Feature: A method must be attached to an object, assigning a function to a property of an object, then it becomes a method, where this refers to the attached object.

Like what:

function f () {

   This.method = function () {};
}
var o = {

}

3.
Constructor Invocation mode

Characteristics:
1. Use the New keyword to guide the constructor.
2. The constructor sends this in the same way as the method, representing the object, but the object in the constructor is the object that was just created
3. Return is not required in the constructor, the default return this

Add:
1. If you add the return manually, it is equivalent to the return this
2. If you manually add the return base type; Invalid, or retain original return this
3. If you manually add the return null; Or return undefiend, invalid
4. If you manually add the return object type; Then the original created this will be discarded, returning the object after return

Because the constructor simply adds a member to this. Didn't do anything else. And the method can do this,
Constructors are not fundamentally different from methods.

1. Factory Method

//Factory is used for production, so if the function creates an object and returns it, it is called the function as factory function
function Createperson (name, age, gender) {
var o = {};
o.name = name;
o.age = age;
O.gender = gender;
return o;
}

//document.createelement ()

2. Construction Method
3. Parasitic creation of an object

//appearance looks like a construction method, but the nature is not how the construction method creates the object
function Createperson (name, age, gender) {
var o = {};
o.name = name;
o.age = age;
O.gender = gender;
return o;
}
var p = new Createperson (' Jim ', ' n ', ' Male ');

4. Mixed-type creation

One case:
<! DOCTYPE h

<meta charset= "UTF-8" >
<title></title>
<body>
</body>
<script>

function Foo () {
GetName = function () {alert (1);};
return this;
}
function GetName () {
Alert (5);
}
Foo.getname = function () {alert (2);};
Foo.prototype.getName = function () {alert (3);};

GetName = function () {alert (4);};

Foo.getname (); 2
GetName (); 4
Foo (). GetName ();//11 Start assigning global GetName to 1 and return this

GetName (); 1
New Foo.getname (); 2
New Foo (). GetName (); 3

New New Foo (). GetName (); 3

</script>



4. Context Invocation Mode

The context is the environment, which is the meaning of the custom setting this.

Syntax:
1. Name of the function. Apply (object, [parameter]);
2. Name of the function. Call (object, parameter);

Description:
1. The function name is the function itself, and the default this is the global variable when calling using a function
2. The function name can also be provided by the method, which refers to the current object when the method call is used.
3. After the call is made with apply, neither the function nor the method is valid. Our this is determined by the first parameter of apply

Note:
1. If the function or method does not have this operation, then no matter what the invocation is actually the same.
2. If the function calls Foo (), then it is a bit like foo.apply (window).
3. If the method calls O.method (), then it is a bit like o.method.apply (o).

parameter Issues

either call or apply in the case of no subsequent arguments (no arguments to the function, no arguments to the method) are exactly the same.

function foo () {
Console.log (this);
}
foo.apply (obj);
Foo.call (obj);


the use of the first parameter is also a regular
1. If an object is passed in, it is equivalent to setting the This parameter in the function
2. If you do not pass in the parameter, or pass in null. Undefiend and so on, then the equivalent of this defaults to window


foo ();
foo.apply ();
foo.apply (null);
foo.call (undefined);


3. If the basic type is passed in, then this is a reference to the wrapper type of the base type

number, number
Boolean, Boolean
String- string


# # Except for the parameter outside this parameter

When using context invocation, the original function (method) may have parameters, then this parameter is used in the context call to represent the second (nth) parameter
```
function foo (num) {
console.log (num);
}
foo.apply (NULL, [123]);
//equivalent to
foo (123);


Application

The context call can only modify this, but the most used place is the borrowing function call.

convert a pseudo-array to array

the traditional approach

var a = {};
a[0] = ' a ';
a[1] = ' B ';
a.length = 2;

///array self-bringing method concat
//Syntax: Arr.concat (1, 2, 3, [4, [5]]);
//feature does not modify the original array
var arr = [];
var newArr = Arr.concat (a);


because A is a pseudo-array, it just looks like an array. That's why it's not here, but the Apply method has a feature that can use an array or a pseudo-array as a parameter

foo.apply (obj, pseudo-array);//IE8 not supported


use a as the second parameter of apply

var newArr = Array.prototype.concat.apply ([], a)


The process of array conversion is actually to take out the elements one after another to form a new array, all the methods involved in the operation can theoretically

1. Push, Unshift
2. Slice
3. Splice

Push Method


usage: arr.push (1); Adds this element to the array and returns the number of elements added
Arr.push (1, 2, 3); Add these three elements to the array in turn, returning the added number

var a = {length:0};//pseudo-array
a[a.length++] = ' abc ';//a[0] = ' abc '; a.length++;
a[a.length++] = ' def ';

//Use an empty array to place the elements in an array
var arr = [];
Arr.push (a);//Do not expand the element at this time, but instead add the pseudo-array as an element to the array
//Use apply again to expand the characteristics of a pseudo-array
arr.push.apply (arr, a);
//Use Apply to expand the properties of the pseudo-array, which is equivalent to Arr.push (A[0], a[1])


Slice


syntax: Arr.slice (Index, EndIndex)
If the second argument is not passed, then it is obtained from index consistent to the end
The method does not modify the original array

var a = {length:0};
a[a.length++] = ' abc ';
a[a.length++] = ' def ';

//If he is an array, it should be intercepted from 0 to the last
//If possible, should be A.slice (0)
//But he doesn't have the means .
//Borrow the slice of the array to convert this to this pseudo-array

var arr = [];
var newArr = arr.slice.apply (A, [0]);



to find the largest value in an array

Traditional

var max = arr[0];
For (var i = 1; i < arr.length; i++) {
if (arr[i] > max) {
...
}
}




or use Apply to expand the properties of the array

var arr = [123456,12345,1234,345345,234,5];
Math.max.apply (null, arr);


borrowing constructor Inheritance


function person (name, age, gender) {
this.name = name;
this.age = age;
This.gender = gender;
}

//need to provide a Student constructor to create a student object
//Students should also have name, age, gender, and also need to have course courses
function Student (name, age, gender, course) {

Person.call (this, name, age, gender);

this.course = course;
}

Chat: Four invocation patterns of functions in JavaScript

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.