JavaScript Ninja cheats Fourth Chapter notes (function Advanced) __ function

Source: Internet
Author: User
Tags assert javascript array
anonymous function: is a function without a name

Such as:

function () {assert (True, ' power! ')}

var ninja={shot:function () {assert (True, ' ninja! ')}}
Ninja.shot ();

settimeout (function () {assert (True, ' forever! ')},500)

All of these are anonymous functions, and some places do not need function names. The basic anonymous function appears

The appearance of anonymous functions is that it allows us to create smaller units of execution, instead of creating a large number of command-statement functions that gracefully implement recursion:

The answer is: callee arguments has a callee attribute that refers to the function that is currently executing

Example:

var ninja={
    chirp:function (n) {return
        N>1?arguments.callee (n-1) + '-chirp ': ' Chirp ';
    }

Assert (NINJA.CHIRP (3) = = ' Chirp-chirp-chirp ', "yes");
treat a function as an object

The functions in JavaScript are different from those in other languages, and JavaScript gives a lot of features to the function, the most important feature is the function as the first object

A function can have properties and methods, variables, all the attributes of ordinary objects owned by all ordinary objects, and most importantly, can be invoked

To add a property to a function:

var obj={};
var fn=function () {};
Obj.prop= "Hitsuke (Distraction)";
fn.prop= "Tanuki (climbing)"
function Storage:
    var store={
        nextid:1,
        cache:{},
        add:function (FN) {
            if (!fn.id) {
                fn.id=store.nextid++;
                Return!! (STORE.CACHE[FN.ID]=FN);
            }
        }
    Function Ninja () {

    }
    Console.log (Store.add (Ninja))
    Console.log (!store.add (Ninja))

You can see Add (), first determine if there is an ID in the incoming FN, and if not we add the id attribute in FN, with ID as key and FN as value, and a Method (Ninja ()) is saved.

The second time an id attribute is present, the self-memory function is no longer added

Caching memory is the process of building a function that remembers previously computed structures. Avoid the need for complex computations that have been performed, which can significantly improve performance

The best thing to remember is the DOM element ...

Let's look at one example:

function IsPrime (value) {
    if (!isprime.anwers) isprime.anwers={};
    if (isprime.anwers[value]!=null) {return
        isprime.anwers[value];
    }
    var prime=value!=1;
    for (Var i=2;i<value;i++) {
        if (value%i==0) {
            prime=false;
            Break
        }
    {
    isprime.anwers[value]=prime;
}
Console.log (IsPrime (5));
Console.log (Isprime.anwers[5]);

You can see the anwers attribute in the IsPrime, and you can get the result directly if you pass in the second time

is actually equivalent to doing a cache of this function, with a cached function, and if you're using a memory DOM element, how much more efficient do you think?

    function getelements (name) {
        if (!getelements.cache) getelements.cache={};
        return getelements.cache[name]=getelements.cache[name]| |
                document.getElementsByTagName (name);
    

The book says it's 5 times times more efficient. variable-length argument list use apply to support variable parameters

Math.max ();
If you want to find the maximum value, you have to.
Math.max (1,2,3,4);
You want to be able to pass in an array, let him find, in fact, the JavaScript array method is not looking for the maximum value, and the Max method does not support the array, how to do?

Remember to apply, is the third chapter introduced him, and now have not forgotten it

The first argument to apply is the specified context this, and the second is the array, and he can turn the array into a parameter-passing method

Math.max.apply (Math,array);

Here's an extension, what would you do if you wanted to multiply the first and the maximum of the variable parameters in the variable parameters passed in by the method?

Remember that arguments is a pseudo array, you can't do it with the slice method

What will you think of this time?

No mistake.

function multi (mulit) {return
    mulit*math.max.apply (Math,array.prototype.slice.call (argument,1));
}

Argument camouflage array to use the Slice method function overload

overload, usually with different parameters of the same name, generally for other object-oriented languages such as Java

And JavaScript isn't like that.

We overload, only one implementation, but the implementation of the internal is through the parameters of the characteristics and number of the corresponding changes to achieve the purpose

But if you have any other language experience, I say the words above, I should know how to make it happen.

Whatever:function () {
    switch (arguments.length) {case
        0:
        //do some break
        ;
        Case 1:
        //do some break
        ;
    }

But we still have to snap like other language-oriented, not

Here you have to know that the function also has attributes called length, not to be confused with the length of argument

By length We can tell how many named arguments are declared.

By Arguments.length, you know how many parameters are passed in at the time of the call

Start:

   function Addmethod (object, name, fn) {var old=object[name]; Object[name]=function () {debugger if (fn.length==arguments.length) {return Fn.app
            Ly (this,arguments);
        }else if (typeof old== ' function ') return old.apply (this,arguments);
    } var ninja={values:[' One ', ' two ', ' three '};
    Addmethod (Ninja, ' What ', function () {return this.values;
        }) Addmethod (Ninja, ' What ', function (a) {var ret=[]; for (Var i=0;this.values[i].length;i++) {if (This.values[i].indexof (a) ==0) Ret.push (this.values[
            I]);
        return ret;
        }) Addmethod (Ninja, ' What ', function (a,b) {var ret=[]; 
            for (Var i=0;this.values[i].length;i++) {if (this.values[i]== (A + ' +b)) Ret.push (this.values[i));
        return ret;
    }) Console.log (Ninja.what (). length==3); Console.log(Ninja.what (' one '). length==1);
    Console.log (Ninja.what (' One ', ' two '). length==1); Console.log (Ninja.what (' One ', ' two ', ' three ') ==null);

First look at the Addmethod method The third parameter passed the anonymous method, and the parameter was 1,2,3.

The main logic of Addmethod is object as storage carrier, name is Key,value anonymous method

If this is not the only way to achieve overload, we continue to look at the following logic

function () {
            if (fn.length==arguments.length) {return
                fn.apply (this,arguments);
            } else if (typeof old== ' function ') return
                old.apply (this,arguments);
        }

Explain the code in terms of execution code logic

Finally, 2 parameters were passed in.

  Addmethod (Ninja, ' What ', function (a,b) {...}

Simply calling Addmethod does not execute anonymous methods.

What's really going to call is the following

Console.log (Ninja.what (). length==3);

While executing this code, the anonymous method is executed,fn.length is 2, because it does pass in the last two arguments,

The named and incoming arguments are equal to the anonymous method, but there are no incoming arguments

When not equal, executes

var old=object[name];
Old.apply (this,arguments);

In fact, this is recursive, keep calling several anonymous methods stored until the named and passed parameters are equal, that is, the previously stored anonymous method without parameters

You don't understand, you can run the whole block of code debug again.

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.