JavaScript functions and scopes (vi)

Source: Internet
Author: User
Tags modulus

Focus.

First, the function

A function is a piece of JavaScript code that is defined once, but can be executed and called multiple times. JS functions are also objects, so the JS function can be like other objects to manipulate and pass, so we also often called JS function as a function object.

Attention:

The return value of the function, which relies on the return statement.

General function Call: If there is no return statement, the default is to return undefinedafter all the code has finished executing.

If it is used as a constructor, the external uses new to call, if there is no return statement, or return is the basic type, The default will return this as.

Conversely, if the return is an object , the object is used as the return value of the new constructor.

The function content is more, the emphasis is:

    • This
    • Arguments
    • Scope
    • Different invocation methods
      • Call Foo () directly
      • Object Method O.method ()
      • Constructor New Foo ()
      • Call/apply/bind call Func.call (o)
    • different ways to create
Second, function declaration and expression 1, function declaration
function Add (A, b) {    A=+A;    b=+b;     if (IsNaN (a) | | IsNaN (b)) {        return;    }     return A +b;}

A complete statement begins with a function, without parentheses, without an exclamation mark, does not enclose it, and does not wait for the right value of an assignment statement. The function defined in this way is called a function declaration.

2. function expression 1, function variable

A function expression assigns a value to a variable.

// functional variable Function variable var add=function(A, b    ) {//dosth}
2. Execute function expression immediately (IEF)

Enclose an anonymous function in parentheses before invoking it directly.

// immediately execute function expression IEF (Immediately Executed function) (function() {})();
3. function expression as return value

The function object is the return value, and the function is the object.

// first-class function return function () {    //dosth}
4. Named function expression (not used)

is also assigned to a variable, but this function is not an anonymous function, but a function with a name,

// NFE (Named Function Expression) var add=function(A, b    ) {//dosth}
3. The difference between function declaration and function expression

The main difference is that the function declaration is pre-placed.

function declarations, which can be called before a declaration, because the pre-session is placed.

function expression called before declaration error: Undefined is not a function.

In an expression of a function

var add=function (A, b) {//do sth};

The declaration of the variable is to be advanced, and the Var add will be advanced, and the value of the add is undefined.

An exception is reported when a undefined variable is attempted to be called as a function: undefined is not a function.

4.namingfunction expression (NFE)

Classic Bug

The name Nfe in a named function expression is normally inaccessible in the scope where the function object is created. So error: NFE is notdefined

The old IE browser (ie6~8) is still accessible, but NFE and Func are not the same object.

named function expressions apply :

Debugging

Call yourself recursively

// Recursive invocation var func=function nfe () {/* * do sth. * */NFE ();}
5. Function constructor

In addition to function declarations and function expressions, there is an uncommon way of constructors-using the function Builder.

There can be more than one parameter in function (), the preceding parameter represents the formal parameter inside the functional object, and the last parameter represents the code inside the function body .

The code in the body of the function is also a string, which is why the constructor is not commonly used.

var func=New Function (' A ', ' B ', ' Console.log (a+b); ' ); // create an object with A,B2 parameters, and inside the function body is the output a+bfunc (x); // 3 // The result is the same regardless of whether you use new or not.  var func=function (' A ', ' B ', ' Console.log (a+b); ' ); func (N); // 3
function constructor scope and other processing differences from general function declarations and function expressions

1, the variables created inside the function constructor are still local variables,

// CASE1 Function (' var localval= ' local '; Console.log (localval); ') (); // immediate Execution of Console.log (typeof Localval);     // undefined

2. The function declaration can access the global variable, but it cannot access the variable defined in its outer function.

Local is not accessible, globally global can be accessed.

Third, THIS1, the global this (browser)

This general in global scope points to the global object, and the browser Rollup Global object is window.

2, the general function of this (browser)

Calling F1 () directly under the global scope, this still points to the global object, which is the window in the browser and the global object in node. js.

In strict mode , call F2 () directly, this execution is undefined.

3. This of the function as an object method

As long as the function as a method of the object O.f,this will point to this object o.

var o={    prop:PNs,    f:function() {        returnthis  . Prop;     // Panax Notoginseng

Or

var o={prop:37}; function Independent () {    returnthis. Prop;} O.F=//PNS
4. This on the object prototype chain

Object o has a property f.

P is an empty object, and the prototype of P points to O. Add 2 attributes A and B to P, and then call P.F ().

Call P.F () when called is the prototype of P o above such a property F. So the this call on the object's prototype chain points to an object.

var o={f:function() {returnthis. A+ this. B}}; var p=object.create (o);p. A=1;p. b=4//5
5. Get/set method and this

The This in the Get Set method is also the object that points to the Get,set method.

functionmodulus () {returnMATH.SQRT ( This. re* This. re+ This. im* This. im);}varo={re:1, Im:-1, get phase () {returnMath.atan2 ( This. IM, This. Re); }}object.defineproperty (O,' Modulus ', {get:modulus, enumerable:true, Configurable:true}) Console.log (O.phase,o.modulus); //-0.7853981633974483 1.4142135623730951
6. This in the constructor

Use MyClass as a constructor.

function MyClass () {    this. a=37;}  var o=New  MyClass (); /* this points to an empty object, and the prototype of the empty object points to Myclass.prototype,this as the return value, because there is no return so the object o will have the attribute a as PNS */ Console.log (O.A); // Panax Notoginseng

Attention:

The return statement returns the object, and the object is returned as a value, so a is 38 below.

function C2 () {    this. a=37;      return {a:38};} o=new  C2 (); Console.log (O.A); //  -
7. Call/apply method and this
function Add (c,d) {    Console.log (this. A+ this. b+c+d);}  var o={a:1,b:3}; // Call calls Add.call (o,5,7); //    //1+3+5+7=16//Apply Call add.apply (o,[10,20]); //    //1+3+10+20=34

Application

function Bar () {    console.log (Object.prototype.toString.call (this));} Bar.call (//[object number]

Call and apply if this passes null or undefined, this will point to the global object, which is the window in the browser.

In the case of strict mode :

Incoming this is null and undefined, and this is null and undefined.

8. Bind and this[ ES5 offers , ie9+ only]

When you want to use an object as this, it is passed in.

functionf () {return  This. A;}varG=f.bind ({A: "Test"}); Console.log (g ()) ;//Test/*bind once, invoke multiple times, still implement such a binding, more efficient than apply and call*/varO={a:37, f:f,g:g};/*The f attribute is assigned a direct F method, and G is assigned to the method just after the binding*/Console.log (O.F (), O.G ()); //Panax Notoginseng "test"/*O.F () is called by the properties of the object and returns the PNs*//*a special point, after binding with the Bind method, even if the new bound method as the object's properties to call, will still follow the previous binding to go, so still return test*/

Application

 This. x=9;//equivalent to window.x=9varmodule={x:81, GetX:function(){return  This. x;}}; Module.getx ();//81 as an object method callvarGetx=module.getx ();//assign the object's method to a variableGetX ();//9 This points to window, which is called the X of windowvarboundgetx=Getx.bind (module); Boundgetx ();//81 Modifying the runtime's this by using bind
Iv. function Attribute Arguments

Foo.length gets the number of formal parameters.

Arguments.length get the number of actual arguments.

Foo.name gets the function name.

pit : Try to modify the value of the arguments[2]=100 Z, or undefined.

That is, if the parameters are not passed in, the arguments and parameters are not changed to modify the binding relationship.

functionfoo (x, y, z) {console.log (arguments.length); //2Console.log (Arguments[0]);//1arguments[0]=10;   Console.log (x); //has a binding relationship, parameter x is modified toarguments[2]=100;//Z not passed inConsole.log (z);//without a binding relationship, Z is still undefinedConsole.log (Arguments.callee===foo);//true, strict mode is forbidden to use}foo (The); Console.log (foo.length);//3Console.log (Foo.name);//"foo"
V. Bind and Function currying

The function of curry is to split a function into multiple units.

1, currying
function Add (a,b,c)    {    Console.log (a+ ' | ') +b+ ' | ' +c);    Console.log (a+b+c);} var func=add.bind (undefined,100); func; // 100|1|2 // 103 var func2=func. bind (undefined,200); Func2 (ten); // 100|200|10 // 310

100 fixed assignment to the a parameter.

Once again, 200 is fixed to the a parameter.

2. Practical examples
/*GetConfig getting a set of configurations may not be the same in different pages, but under the same module, the first 2 parameters may be the same, or some parameters are the same*/        functionGetConfig (colors,size,otheroptions) {console.log (colors,size,otheroptions);}/*This does not matter, write a null or undefined can, may be in a module color is #cc0000,size is 1024x768*/varDefaultconfig=getconfig.bind (NULL, "#CC0000", "1024x768");/*get a generic configuration of defaultconfig such a module level, as soon as the last parameter is passed, it may be a separate configuration under each page*/Defaultconfig ("123");//#CC0000 1024x768 123Defaultconfig ("456");//#CC0000 1024x768 456
Six, bind and new

Called with new, at this level. The role of BIND () is ignored.

With new, even binding bind will be ignored.

Func () is called directly, this will point to the bind parameter {A:1},return THIS.A will return 1.

The execution of this.b=100 actually adds a B property to {a:1}, and finally {a:1, b:100} simply does not return the value because the return value is specified.

New, return returns the value unless it is an object, not an object, and this is initialized to the default empty object, which is a prototype of Foo.prototye.

So when the new Func () is called here, even if we specify the bind method, this will still point to the empty object pointed to when there is no bind. The prototype of an empty object points to Foo.prototype, the B property of the empty object is set to 100, the entire object is returned as a return value, and the return THIS.A is ignored. Therefore, the object literal {b:100} is returned after the call with the new Func ().

Seven, bind method simulation

How to implement the Bind method in the old browser? Simulation implementation.

The Bind method implements 2 functions, binding This and currying .

The simulation implementation of the MDN.

JavaScript functions and scopes (vi)

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.