JavaScript code reuse (iv)-mixing, borrowing methods, and binding

Source: Internet
Author: User

This article continues to say JS's modern reuse mode: mixing, borrowing methods and binding.

Mixing

An extension can be made to the previously mentioned idea of implementing code reuse through attribute replication, which is to mix (mix-in). Mixing does not replicate a complete object, but instead copies any of the members from multiple objects and combines them into a new object.

The implementation of the blend is not difficult, but it is only necessary to iterate through each parameter and copy each property in each object passed to the function.

function Mix () {    var arg,prop,child={};      for (arg=0:arg<arguments.length;arg++) {        for-in  Arg)            {if  (Arguments (ARG). hasOwnProperty (prop)) {                = Arguments[arg][prop];}}    }     return child ;}

Now, with a generic mix-in function, you can pass any number of objects to it, and the result will be a new object with all of the source object properties, an example of a call:

var cake = Mix (    true}    ,true    }, "3 cups"},     "sure!" }); Console.dir (cake);

The following is the output of the console:

      Butter          1     eggs            2     flour           "3 cups"     large             True     sorted          true     sugar           "sure!"

Borrowing method

Sometimes you just need one or two of the existing objects, and while you want to reuse a method, you do not want to inherit the parent-child relationship with the source object, that is, you want to use only the methods you need, and not the other methods that you never use. In this case, you can use the borrowing methods (borrowing method) to do so, that is, using call () and apply (), the difference is the difference between the parameters.

Here is an example of how to borrow an array:

function f () {    var args = [].slice.call (arguments,1,3);     return args;} F (1,2,3,4,5,6); // [2,3]

The empty array is created in order to use the slice method of the array, or it can be borrowed from the prototype of array, that is, Array.prototype.slice.call, which needs to lose longer characters, but can save the work of creating an empty array.
The borrowing method, not through call () and apply () is simply assigned, and within the borrowing method, the object pointed to by this is based on the invocation expression, but more often it is better to lock the value of this, or bind it to a specific object and predetermine the object.

Consider the following example, where one object has a say () Method:

var one = {    "Object",    function(greet) {        return Greet+ "," +this. Name;    }};o Ne.say ("HI"); // "Hi,object"

There is no say method in another object, but it can be borrowed from one:

var = {    "another object"};one.say.apply (two,["Hello"]);   "Hello,another object"

The This in the Say () method borrowed above points to two, so THIS.name is "another object". But in what scenario should a function pointer be assigned a global variable, or will the function be passed as a callback function? There is such an application in the program, and there is a problem.

var say = One.say;say ("HoHo"); // "hoho,undefined" var yetanother = {    "yet another object",    function(callback) {        return callback ("Hola");}    ; Yetanother.method (One.say); // "hola,undefined"

In both cases, this points to the global object, and the code does not run as expected. To bind the relationship between an object and a method, you can use one of the following simple functions:

function bind (o,m) {    returnfunction() {        return  m.apply (o, arguments);}    ;}

Bind () accepts an object O and a method m, binds them together, and then returns another function. The returned function can access O and M through a closed package. So after bind () returns, you can still access O and M. You can use BIND () to create a new function:

var twosay = bind (Two,one.say); Twosay ("Yo"); // "Yo,another Object"

Regardless of how you call Twosay (), this method is always bound to object one.

Bind () in the ES5

ES5 adds bind () to Function.prototype, making bind () as easy to use as call () apply (). You can execute the following expression:

var newfunc = Obj.someFunc.bind (myobj,1,2,3);

is to bind SomeFunc () with MyObj and populate the first 3 parameters of SomeFunc ().
When running under an environment that does not support ES5, see How to Implement Function.prototype.bind ():

if (typeof Function.prototype.bind = = = "undefined") {    Function(Thisarg        ) { var  This ,              = Array.prototype.slice,             = Slice.call (arguments,1);         return function () {            return  fn.apply (Thisarg,args.concat (slice.call (arguments     ));};};

It spliced the parameter list, which is the parameter passed to bind (except the first one), and those passed to the new function returned by bind (), and the new function is called later. One invocation Example:

var twosay2 = one.say.bind (both); Twosay2 ("Bonjour"); // "Bonjour,another Object"

You can also pass a parameter:

var twosay3 = One.say.bind (both, "Nihao"); Twosay3 (); // "Nihao,another Object"

Summary

In JavaScript, it may not be as often as C # or Java to face inheritance problems, some reason is that JS library with some methods to solve the problem, and some reason is that in JS rarely need to establish a long and complex inheritance chain. In static strongly typed languages, inheritance may be the only way to reuse code, but in JS there are often more concise and elegant methods, including methods such as borrowing methods, binding, copying attributes, and mixing attributes from multiple objects. After all, code reuse is the ultimate goal, and inheritance is just one way to achieve this.

--end--

JavaScript code reuse (iv)-mixing, borrowing methods, and binding

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.