Reprinted-interesting anti-kerizalization in javascript

Source: Internet
Author: User
Tags scream

Preface: domestic front-end research is not inferior in some aspects to foreign countries. Although I do not understand this article, I appreciate this spirit of in-depth research!

------------------------------------- Reprint original -----------------------------------

The topic of anti-corialization came from a piece of twitter last year by Brendan Eich, the father of javascript. I 've been studying it for a few days. I think this stuff is very interesting. I 'd like to share it with you. First, forget its name and see what it can do.

Don't underestimate this function. Imagine that when we write a library, we often write such code, taking webQQ's Jx library as an example.


What we want is to borrow some functions on the Array prototype chain. There is no need to explicitly construct a new function to change their parameters and recalculate them.

If the uncurrying method is obviously more elegant and elegant, like this:

You can also do a lot of interesting and convenient things.

You can even use the call and apply methods uncurrying and use the functions as common data. this makes the function calling method in javascript more like its original scheme. When the function name itself is a variable, this call method is particularly convenient.

The call function in scheme is as follows:

Javascript can write very close.

Let's look at the jquery library. Because a jquery object (an object created through $ () is a pseudo array of an object, it has the length attribute and can search for corresponding elements by subscript, when you need to add a member to a jquery object, the pseudocode is probably:

If you use uncurrying, you can

The push function of the array object is used to allow the engine to automatically manage the array member and length attributes.

In addition, you can borrow all the required functions once and for all. A piece of test code:

In general, the use of uncurrying technology can give any object a method of native object. Well, if it still does not interest you, you can do something else.

Next, let's take a look at the principles and implementations.
Before learning about the strange name of Anti-currying, we must first understand currying.

Definition in Wikipedia: currying, also known as partial evaluation, is to convert a function that accepts multiple parameters into a function that accepts a single parameter, and return the technology of the new function that accepts the remaining parameters and returns the result.

In layman's terms, currying is a bit similar to the method of installment payment when buying a house. First, a part of the down payment (some parameters) is given, and a passbook (a function is returned) is returned ), when appropriate, the remaining parameters are given and the value is calculated.

Let's take a look at the currying we 've used. We often implement a function. Prototype. Bind function when binding context.

High-order functions are the basis for implementing currying. The so-called high-order functions must satisfy at least these two features:
1. functions can be passed as parameters,
2. The function can be used as the return value.

At the beginning of JavaScript design, many features of scheme are referenced. Scheme is one of the two major dialects of lisp, the originator of functional language. Therefore, JavaScript also has some functional language features, including high-level functions, closures, lambda expressions, and so on.

When a function in Javascript returns another function, a closure is formed, and the parameters of the first operation can be saved in the closure. We use this idea to write a common currying function.

We agree that the parameter will continue to be currying when it is passed in. If the parameter is null, the value will start to be evaluated.

Assume that we need to record the amount of money spent today before the end of each day to implement a function for calculating the monthly cost. However, we only care about the total cost at the end of each month, and do not need to calculate it every day.

Using the currying function can delay computing until the last moment. The benefit is self-evident. In many cases, unnecessary computation can be avoided to save performance. It is also a method for realizing the value of inertia.

Okay, now I am going to the question,

Curring is prefixed with some parameters.

Anti-curring refers to the transmission of fixed parameters or this context as parameters in the future.

In fact, this is to do the following:

Obj. foo (arg1) // foo is a function only on obj, just like push is originally only on Array. prototype.

Convert to this form

Foo (obj, arg1) // Convert []. push to push ([]), just like in the first example.

Just like a socket originally connected to a TV plug, after removing it, it can also be used to connect the refrigerator.

Each prototype method of Array and String on Ecma is followed by such a paragraph, such as push:

NOTE The push function is intentionally generic; it does not require that its this value be an Array object.
Therefore it can be transferred to other kinds of objects for use as a method. Whether the concat function can be applied.

Why is Javascript designed like this? Let's first review the important duck-type ideas in dynamic languages.

Tell a story:

A long time ago, an emperor liked to hear a duck scream, so he summoned the Minister to form a choir of one thousand ducks. The Minister caught all the ducks in the country and finally kept one. One day, I finally came up with a brave chicken. The chicken said it would scream too. Well, in the settings of this story, it will indeed scream. Later, the story was quite obvious. The chicken was mixed into the duck choir. -The emperor just wants to hear it. He doesn't care whether you are a duck or a chicken.

This is the concept of duck type. In javascript, many functions do not perform object type detection, but focus only on what these objects can do.

The methods on the prototype of the Array constructor and the String constructor are specially designed as the duck type. These methods do not validate the data type of this. This is why arguments can impersonate an array to call the push method.

Let's take a look at the code of Array. prototype. push in the v8 engine:

Function ArrayPush (){
Var n = TO_UINT32 (this. length );
Var m = % _ ArgumentsLength ();
For (var I = 0; I <m; I ++ ){
This [I + n] = % _ Arguments (I); // copy attributes
This. length = n + m; // modify the length
Return this. length;
}
}

As you can see, the ArrayPush method does not limit the display of this type, so theoretically any object can be passed into the ArrayPush visitor.

We need to solve only one problem. How can we use a common method to make an object impersonate an array object.

The real implementation code is actually very simple:

Although this code is very short, it is a little effort to understand it for the first time. Let's take the push example to see what happened to it.

Var push = Array. prototype. push. uncurrying ();

Push (obj, 'first ');

 

 

Original article address:Interesting anti-kerizalization 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.