Four ways to call 6-js functions __ function

Source: Internet
Author: User
Tags wrapper hasownproperty
6. Four ways of calling functions

The function has the following call pattern function call pattern method call Pattern Constructor Mode context mode 1. function call Pattern

To invoke, you must define the definition of the function first: declarative: function Fuc () {} expression: var func = function () {}; function:new function (' parameter ',..., ' function body ');

individually called, is the function call pattern, that is, the function name (parameters), can not add anything else, Object O.fuc () is not.

In function call mode, this represents the Global object window

Any self invocation function is a function pattern. 2. Method call Mode Methods

The so-called method invocation is called by the object's method. What the method is, the method itself is a function, but the method is not separate , but is invoked through an object boot .

This means that the method object must have a host object .

That is, the object. Method (Parameters)

This represents the object of the bootstrap method, which means the host object

Contrast-function Invocation pattern: Method invocation pattern is independent, requires host, and function invocation pattern is independent method invocation mode: Obj.fuc (); Function call pattern mode: fuc (); In method invocation mode, this refers to the host. And in the function call pattern this refers to the Global object window A side question of the American regiment

    var length = ten;
    function fn () {
        console.log (this.length);//
    }
    var obj = {
        Length:5,
        method:function (FN) {
  FN ();   10 is not preceded by a boot object, is the function call mode
            arguments[0] ();//2
            //arguments is a pseudo array object, where the call is equivalent to an index of an array.
            Here this is the pseudo array, so the This.length is 2
        }
    };
    Obj.method (FN, 1);    Print 10 and 2
    //obj.method (FN, 1, 2, 3);    Printing 10 and 4

Analytical:

FN () is not preceded by a boot object, is a function call pattern, this is a global object, output 10

arguments[0] (), arguments is a pseudo array object, where the call is equivalent to an index of an array.

The host is the arguments object, where the object is being booted.

So, when executing, this means arguments, because two parameters are passed, so the output is Arguments.length 2 3. Constructor mode (constructor pattern, constructor mode)

Constructor

Features: booting using new keyword

Execute step: var p = new person ();

New is an operator that is specifically used to request the creation of an object, and the created object is passed to this constructor. The constructor is then initialized with the constructors.

    function person () {
        //new When entering a constructor, the prototype of the P object points to the constructor person, 
        //P.__proto__.constructor = the function person () {};
        //And this refers to the P object
        this.name = ' Jim ',
        this.age =;
        This.gender = ' male ';
    }
    var p = new person ();

When new enters the constructor, the prototype of the P object points to the constructor person

When constructed, this refers to the P object, which is constructed by dynamically adding properties to the object.

Tip: If you call a constructor, the constructor has no arguments, and parentheses can be omitted.

    function person () {
        this.name = ' Jim ';
    }
    var p = new Person; Without reference, it can be abbreviated without affecting the structure
    console.log (p);   P contains the Name property

↑ No reference, can be abbreviated, does not affect the construction

return value

Do not write a return statement, then the constructor returns this by default

In the constructor return basic type (return num, return 1223). The return type is ignored.

In the constructor return reference type , the constructor returns the reference type data and ignores this

    function person () {
        this.name = ' Jepson ';
        return 123;
    }
    var p1 = new Person ();
    Console.log (p1);

↑ ignored 123, returns this object, pointing to the instance of the build

    function person () {
        this.name = ' Jepson ';
        return {' Peter ': ' Nihao '};
    }
    var p1 = new Person ();
    Console.log (p1);

↑ ignores this, returns {' Peter ': ' Nihao '} object constructor binding

If the constructor has no arguments, you can omit the parentheses

var p = new Person;

If you want to create an object and call its methods directly

(New Person ()). SayHello ()

-> can omit to adjust the tuberculous parentheses new person (). SayHello ()

-> If you want to omit the parentheses of a constructor, you must add a tuberculous parenthesis (new person). SayHello () face Test

An interview question, we can try to do first, and then look at the following answers and analysis

What is the order of the following code, alert

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

    Foo.getname ();  Alert??
    GetName ();  Alert??
    Foo (). GetName (); Alert??
    GetName (); Alert??
    New Foo.getname (); Alert??
    New Foo (). GetName (); Alert??
    New New Foo (). GetName (); Alert??

pre-resolution, simplified code, and answers

    /* Function GetName () {alert (5);} execution to below is overridden, direct deletion of
    /function Foo () {
        getName = function () {alert (1);};
        return this;
    }
    Foo.getname = function () {alert (2);};
    Foo.prototype.getName = function () {alert (3);};
    var getName = function () {alert (4);};

    Foo.getname ();  -------Output 2-------
    getName ();      -------Output 4-------
    Foo (). GetName ();    -------Output 1-------
    getName ();  -------Output 1-------
    new Foo.getname ();     -------Output 2-------
    new Foo (). GetName ();    -------Output 3-------
    var p = new New Foo (). GetName ();     -------Output 3-------

all parsing process ↓

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

    var getName = function () {alert (4);};  Foo.getname ();

    -------Output 2-------//Invoke the Foo function as an object dynamically added property method GetName//Foo.getname = function () {alert (2);};      GetName ();

    -------Output 4-------//The Foo function has not yet been executed, GetName has not been overwritten//So here is the top getName = function () {alert (4);};    Foo (). GetName ();
    -------Output 1-------//Foo (), overwrite the global getName before returning this,//This is window, Foo (). GetName () is called Window.getname
    At this point the global getname has been overwritten with function () {alert (1);};  So the output 1/* From here starts Window.getname has been covered with alert 1 * * GetName ();

    --------Output 1--------//Window.getname alert (1);     New Foo.getname (); -------Output 2-------//New is to find the constructor (), which is associative by the constructor, and cannot be omitted () even if Foo has no parameters, so it is not foo (). GetName ()//So Foo.getname is a Overall, equivalent to New (Foo.getname) ();
    And Foo.getname is actually the reference//That new (Foo.getname) () of function functions () {alert (2);}, that is, instantiating an object with Foo.getname as the constructor. is similar to the new person (); Person is a constructor//summary to see New (Foo.getname) ();    is to construct the object//constructor with the function () {alert (2);} alert (2) and output 2 new Foo (). GetName ();
    -------Output 3-------//new is to find the constructor (), equivalent to (new Foo ()). GetName (); Executes the new Foo () => with Foo as the constructor, instantiating an object//(new Foo ()). GetName; Accessing the GetName property//instance object of this instantiated object has no GetName property of its own, is not added at the time of construction, cannot find it, finds it in the prototype Foo.prototype.getName = function () {A Lert (3);
    }; It's in the prototype, found it, so (new Foo ()). GetName ();     Execute, alert (3) var p = new New Foo (). GetName (); -------Output 3-------//new is to find the constructor (), equivalent to New ((New Foo ()). GetName) () Output 3//(new Foo ()). Getnam E//New foo () with Foo as the constructor, instantiate the object//New Foo (). GetName Find the GetName property of the instance object, not yourself, find it in the prototype,//Discover Foo.prototype.getName = function () {alert (3);}; Found/So the innermost (newFoo ()). GetName is a prototype property//property value for an object that is instantiated with Foo () () the Reference//So outer new (new Foo ()) of a function function () {alert (3);}. GE
 Tname) () () executes alert (3) in the constructor instance//construction process with the function function () {alert (3);} as the constructor, output 3
4. Context Invocation Pattern

Is the environment call pattern => different invocation patterns in different environments

In short, it is unified one format, can realize function pattern and method pattern

-> syntax (distinguishing) Call form, function name. Call (...) apply form, function name. Apply (...)

the two forms function exactly the same, and the only difference is the form of the parameter. Learn to apply first, then see Call form invocation form of the Apply method

The purpose of a context call is to implement method borrowing and not pollute the object.

If you need to make a function call as a function, you can use the

Foo.apply (NULL); Context is window

If you want him to be a method invocation pattern, note that you need to provide a host object

Foo.apply (obj); Obj object with context as pass

    function foo () {
        console.log (this);
    }
    var o = {name: ' Jim '};

    If you need to make a function call as a function, you can use
    foo.apply (null);//This  => window  //or foo.apply ()

    ///If you want him to be the method call mode, note Need to provide a host object
    foo.apply (o)  //This => O object
how a function with parameters implements a context call.
    function foo (NUM1, num2) {
        console.log (this);
        return NUM1 + num2;
    }

    function call Mode
    var res1 = foo (123, 567);

    Method calls
    var o = {name: ' Jim '};
    O.func = foo;
    var res2 = O.func (123, 567);

Called using apply, if the function is parameterized. The first argument to apply is either null or an object

If NULL is the function call

If the object is a method call, the object is the host object, followed by an array parameter, and all of the function's arguments are placed in the array in turn.

    For example: function mode        foo (123, 567);
          Apply         foo.apply (null, [123, 567]) executes apply with window

    If there is a function call:   func (' John ', 19, ' Male '),
    modify it to AP  Ply mode:  func.apply (null, [' John ', 19, ' Male '])

    method mode:           O.func (123, 567)
    apply               var o = {name: ' Jim ' };
                        Foo.apply (o, [123, 567]); Execute apply with O as context
method of borrowing cases

requirement, get div with P tag, and add border border:1px solid red

General Practice:

    var p_list = document.getelementsbytagname (' P ');
    var div_list = document.getelementsbytagname (' div ');

    var i = 0;
    for (; i < p_list.length; i++) {
        p_list[i].style.border = "1px solid red";
    }
    for (i = 0; i < div_list.length i++) {
        div_list[i].style.border = "1px solid red";
    }
Using method to borrow optimization, element acquisition
    var t = document.getElementsByTagName;
    var p_list = t.apply (document, [' P ']);  Method
    to borrow var div_list = t.apply (document, [' div ']);//method to borrow

Next, consider the following optimizations, two for loops, as long as the array is merged, you can use only a for loop

Array merging

    var arr1 = [1, 2, 3];
    var arr2 = [5, 6];
    Arr1.push.apply (arr1, arr2);  Method Invocation, the first to give an object
    //equivalent to Array.prototype.push.apply (arr1, ARR2);

So similarly, using the Apply method to borrow, combine two pseudo arrays into the same array

    var arr = [];   Pseudo arrays do not have a push method, so here you declare an array
    arr.push.apply (arr, p_list);  The contents of the p_list, each as a parameter put in, equivalent to do not have to traverse the
    arr.push.apply (arr, div_list);//Ibid., method borrow
    Console.log (arr);

Combine the two, use foreach, and the final 6 lines are resolved.

    var t = document.getelementsbytagname, arr = [];
    Arr.push.apply (arr, t.apply (document, [' P ']));
    Arr.push.apply (arr, t.apply (document, [' div ']));
    Arr.foreach (function (val, index, arr) {
        Val.style.border = ' 1px solid red ';
    });
Call calls

When you use the Apply call, the function arguments must be in the form of an array. But there are times when array encapsulation is more complicated

So the call invocation is introduced, and the call invocation is exactly the same as apply, except that the parameter does not need to use an array

    Foo (123, 567);

    Foo.apply (null, [123, 567]);

    Foo.call (NULL, 123, 567);

function calls: Functions name. Call (null, parameter 1, parameter 2, parameter 3 ...);

Method invocation: Function name. Call (obj, parameter 1, parameter 2, parameter 3 ...);

Apply and call are exactly the same when you do not pass the argument. To use the constructor method to implement inheritance

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

    function Student (name, age, gender, course) {
        //prototype chain structure does not change, while implementing the inherited effect
        Person.call (this, name, age, gender); Borrow person construction method
        This.course = course;
    }

    var p = new Student (' Jim ', ' Male ', ' front end ');
    Console.log (P);
Supplementary Knowledge 1. The Bind method of the function (ES5)

Bind is binding.

Or the above case get div and P tags, and add a border border:1px solid red

    var t = document.getelementsbytagname, arr = [];
    Arr.push.apply (arr, T.call (document, ' P '  ));
    Arr.push.apply (arr, T.call (document, ' Div '));
    Arr.foreach (function (val, index, arr) {
        Val.style.border = ' 1px solid red ';
    });

We let the t contain the function body (the way it is) and include the object, which makes it more streamlined

    var t = Document.getElementsByTagName.bind (document), arr = [];
    Arr.push.apply (arr, t (' P '));
    Arr.push.apply (arr, t (' div '));
    Arr.foreach (function (val, index, arr) {
        Val.style.border = ' 1px solid red ';
    });

Bind: Is the use of a function to bind objects

The function itself is callable, but if it wants to be invoked as a method, it must pass in the host object and use the call or Apply form

But bind allows my function to bind to an object, so when calling a function, it is as if the object is calling a method, and it can be passed directly, without having to pass the host object.

syntax: Functions. Bind (Object)

Returns a function of Foo, then call the Returned function foo, as if the bound object is calling the method

     T.call (document, ' P ');

     T (' P '); After binding, the host object is not passed, and the context is changed to document

     bind is the function call method given by ES 5
Supplementary Knowledge 2. Members of the Object.prototype

Object.prototype member Constructor hasOwnProperty determines whether the property is provided for itself propertyisenumerable determine whether the property can enumerate isprototypeof to determine if it is a prototype object ToString, toLocaleString, valueof

    function person () {
        this.name = ' Jim ';
    }
    Person.prototype.age =;
    var p = new person ();
    Console.log (P.hasownproperty (' name '));  True Whether p contains the name attribute, regardless of
    console.log (' age ') on the prototype (p.hasownproperty);  P contains the age attribute

    /* Person.prototype is a prototype of P/
    Console.log (p.isprototypeof (Person.prototype));//False
    C Onsole.log (Person.prototype.isPrototypeOf (P));  True

Use: Generally copy an object to another object, you can judge, more rigorous, in order to prevent the prototype of the property also copied past ... Supplementary Knowledge 3. Packing Type

Strings string is a basic type and should not theoretically contain methods

So charAt, substr, slice, ... And so on, it shouldn't theoretically be there, but it does.

So introduce the concept of packaging objects , in JS in order to better use the data, for three basic types of the corresponding object type number String Boolean

Basic data types are often used in development, but basic data types do not have methods, so the JS engine automatically converts the base type to object type when needed, which is the wrapper object

"ABC". CHARAT (1)

"ABC"-> s = new String ("abc")

S.charat (1) After returning the result, S is destroyed.

When the basic type, the method. The interpreter first converts the base type to the corresponding object type, and then calls the method.

The object is immediately reclaimed after the method execution is completed

Conversions occur when apply and call are invoked. the first parameter of a context call must be an object . If a number is passed, it is automatically converted to the corresponding wrapper type Supplementary Knowledge 4. The grammatical sugars of getter and setter (ES5)

grammatical sugars: the grammatical structure given to facilitate development

itself to achieve:

    var o = (function () {
        var num = 123;
        return {
            get_num:function () {return
                num;
            },
            set_num:function (v) {
                num = v;
            }
        };
    })();
    Want to obtain data  in the form of an object
    o.get_num ();            => o.num form

    wants to set  the data in the form of an object
    o.set_num (456);       => o.num = 456 form

so the getter and setter were born

    var o = (function () {
        var num = 123;
        return {
            //Get Name () {logical body} get
            num () {
                console.log (' Execute Getter Reader ');
                return num;
            },

            //Set name (v) {logical body}
            set num (v) {
                console.log (' Execute Setter Reader ");
                num = v;
            }
        ;
    }) ();

    Console.log (o.num);   Execute Getter Reader the   123
    o.num = 33;//execute Setter reader/writer
    Console.log (o.num);//execute Getter Reader 33

Why not use the object directly? var o = {num:123}, can also read and write it?

Because the grammatical sugar can also limit the range of its assignment , which is particularly cool to use.

    var o = (function () {
        var num =;
        return {

            //Get Name () {logical body} get
            num () {
                console.log (' Execute Getter Reader ');
                return num;
            },

            //Set name (v) {logical body}
            set num (v) {
                console.log (' Execute Setter Reader ");

                if (V < 0 | | | v >) {
                    console.log (' Assignment out of range, unsuccessful ');
                    return;
                }
                num = v;
            }
        ;
    }) ();
    O.num =-1;         Execute setter read/write device
                    assignment out of range, unsuccessful
Supplementary Knowledge 5. Partial array method introduced in ES5ForEach Map Filter Some every indexOf LastIndexOf

ForEach, array traversal call, traversal arr, parameter three 1, 2 index, 3 entire array

     var arr = [' Hello ', ' js ', {  }, function ()

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.