Talking about several borrowing methods in JavaScript--basic knowledge

Source: Internet
Author: User
Tags arrays data structures inheritance lowercase

Objective

By using the call (), apply (), and bind () methods, we can easily borrow the methods of other objects without inheriting it from these objects.

Borrowing methods in JavaScript

In JavaScript, you can sometimes reuse functions or methods of other objects, not necessarily the object itself or the stereotype. By using the call (), apply (), and bind () methods, we can easily borrow the methods of other objects without inheriting them. This is a common tool for professional JavaScript developers.

Prototype method

In JavaScript, almost all data is an object in addition to the original data types that cannot be changed, such as String, number, and Boolean. Array is an object that is suitable for traversing and converting ordered sequences, and its prototypes include slice, join, push, and pop methods.

A common example is when objects and arrays are data structures of list types, objects can "borrow" methods from an array. The most common way to borrow is Array.prototype.slice .

function MyFunc () {
 
  //error, arguments is ' a array like object, ' not ' a real array
  arguments.sort ();
 
  "Borrow" the array method slice from its prototype, which takes an array like object (Key:value)
  //and returns a R EAL array
  var args = Array.prototype.slice.call (arguments);
 
  Args is now real Array, so can use the sort () method from Array
  args.sort ();
 
}
 
MyFunc (' bananas ', ' cherries ', ' apples ');

The Borrowing method works because the call and apply methods allow functions to be invoked in different contexts, which is a good way to reuse existing functionality without inheriting other objects. In fact, arrays define many common methods in prototypes, such as Join and filter:

Takes a string "abc" and produces "A|b|c
Array.prototype.join.call (' abc ', ' | ');
 
Takes a string and removes all non vowels
Array.prototype.filter.call (' Abcdefghijk ', function (val) {
  return [' A ', ' e ', ' I ', ' o ', ' U '].indexof (val)!==-1;
}). Join (")";

As you can see, not only can objects borrow the array's methods, but strings can also. However, because the generic method is defined on a prototype, you must use or when you want to borrow the method String.prototype Array.prototype . This is long-winded and will soon be annoying. A more efficient approach is to use literal amounts to achieve the same goal.

Use literal method of borrowing

Literal is a grammatical structure that follows JavaScript rules, as MDN explains:

In JavaScript, you can represent values by using literal quantities. They are fixed values, not variables, which are literally given in the script.
The literal can be abbreviated to the prototype method:

[].slice.call (arguments);
[].join.call (' abc ', ' | ');
Touppercase.call ([' lowercase ', ' words ', ' in ', ' a ', ' sentence ']). Split (', ');

This looks less verbose, but it must be done directly on [] and "" to borrow the method, still a bit ugly. You can use variables to hold references to literal quantities and methods, which is easier to write:

var slice = [].slice;
Slice.call (arguments);
var join = [].join;
Join.call (' abc ', ' | ');
 
var touppercase = '. toUpperCase;
Touppercase.call ([' lowercase ', ' words ', ' in ', ' a ', ' sentence ']). Split (', ');

With a reference to the Borrowing method, we can easily invoke it with call (), which can also reuse code. With the principle of reducing redundancy, let's see if we can borrow the method without having to write call () or apply () on each invocation:

var slice = Function.prototype.call.bind (Array.prototype.slice);
Slice (arguments);
 
var join = Function.prototype.call.bind (Array.prototype.join);
Join (' abc ', ' | ');
 
var touppercase = Function.prototype.call.bind (String.prototype.toUpperCase);
toUpperCase ([' lowercase ', ' words ', ' in ', ' a ', ' sentence ']). Split (', ');

As you can see, it is now possible to use the Function.prototype.call.bind "borrowed" method of static binding from different prototypes. But var slice = Function.prototype.call.bind(Array.prototype.slice) how does this actually work?

Understanding Function.prototype.call.bind

Function.prototype.call.bindIt's a bit complicated at first glance, but it's very helpful to understand how it works.

Function.prototype.call is a reference that can be "called" and set its "this" value to be used in a function.
Note "Bind" returns a new function that holds its "this" value. Therefore, the .bind(Array.prototype.slice) "This" of the new function returned is always Array.prototype.slice the function.

To sum up, the new function calls the "call" function, and its "This" is the "slice" function. Calling Slice () points to the previously qualified method.

Ways to customize objects

Inheritance is great, but developers often use it when they want to reuse common functionality between objects or modules. There is no need to use inheritance only for code reuse, because in most cases a simple method of borrowing can be complicated.

We've only discussed borrowing the native method before, but it's OK to borrow any method. For example, the following code can calculate the player score for an integral game:

var scorecalculator = {
  Getsum:function (results) {
    var score = 0;
    for (var i = 0, len = results.length i < len; i++) {
      score = score + results[i];
    }
    Return score
  },
  getscore:function () {return
    scorecalculator.getsum (this.results)/this.handicap;
  }
};
var player1 = {
  results: [To, of,],
  handicap:8
};
 
var player2 = {
  results: [4, $],
  handicap:5
};
 
var score = Function.prototype.call.bind (scorecalculator.getscore);
 
score:24.375
console.log (' Score: ' + Score (player1));
 
Score:17
console.log (' Score: ' + Score (player2));

Although the above example is blunt, it can be seen that, like native methods, user-defined methods can be easily borrowed.

Summarize

Call, bind, and apply can change the way functions are invoked and are often used when borrowing functions. Most developers are familiar with the use of native methods, but rarely use custom methods.

In recent years JavaScript's functional programming development is good, how to use Function.prototype.call.bind borrowing method is more convenient? It is estimated that such topics will become more common.

These are the full contents of the Borrowing method in JavaScript, and I want to help you learn about how to borrow 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.