Write high-quality JS code in

Source: Internet
Author: User

2. Using functions

The function provides the programmer with the main abstraction function and the implementation mechanism. Functions can implement many different features in other languages independently, such as procedures, methods, constructors, and even classes or modules.

2.1 Understanding the differences between function calls, method invocations, and constructor calls

For object-oriented programming, the constructors of functions, methods, and classes are three different concepts.

Usage mode: 1, Function call

function Hello (username) {    return "Hello" + username;}

2, method invocation

var obj = {    hello:function () {        return "Hello," + this.username;    },    username: "Floralam"};ohj.hello (); /"Hello,  Floralam"

This variable is bound to an object because the Hello method is defined in the Obj object, and we can also assign a copy of the same function reference in another object and get the same answer.

var obj2 = {    Hello:obj.hello (),    username: "Floralam"};

3, the constructor uses

function User (name,passwordhash) {    this.name = name;    This.passwordhash = PasswordHash;}

Calling user using the new operator is considered a constructor.

var u  = new User ("Floralam", "123");

Unlike a function call and a method call, a constructor call takes a completely new object as the value of the this variable and implicitly returns the new object as the result of the call . The primary function of the constructor is to initialize the new object.

2.2 Proficiency in higher order functions

Higher-order functions are simply functions that use functions as parameters or return values, and functions as arguments (often called callback functions, because the higher-order function "subsequently calls" it) is a particularly powerful, expressive idiom, and is used extensively in JS programs.

Considering the standard sort method for arrays, the sort method requires the caller to decide how to compare any two elements in the array in order to work on all arrays.

function Comparenumber (x, y) {    if (× < y) {        return-1;    }    if (x > Y) {        return 1;    }    return 0;} [3,1,4,1,5,9].sort (Comparenumbers);//[1,1,3,4,5,9]
[3,1,4,1,5,9].sort (function (x x    < y) {        return-1;    }    if (x > Y) {        return 1;    }    return 0;}); /[1,1,3,4,5,9]

The above example is further simplified using an anonymous function.

Learning to use higher-order functions often simplifies code and eliminates tedious boilerplate code. A simple way to convert an array of strings we can use loops to implement:

var names = ["Fred", "Wilma", "pebbles"];var upper = [];for (var i = 0,n = Names.length;i< n;i++) {    Upper[i] = names[i ].touppercase ();} upper;//["FRED", "WILMA", "Pebbles";

Using the easy-to-use map method, you can eliminate loops and convert elements by using just one local function.

var names = ["Fred", "Wilma", "pebbles"];var upper = Names.map (function (name) {    return name.touppercase ();}); upper;//["FRED", "WILMA", "Pebbles";

Also, for example, we want to create several methods to create different strings, with common implementation logic, and each loop creates a string by connecting the results of each independent part.

1 function bulidstring (n,callback) {2     var result = ""; 3 for     (var i = 0; i < n; i++) {4         result + = callback (i); 5     } 6     return  result; 7} 8  9 var Alphab ET = bulidstring (26,function (i) {Ten     return String.fromCharCode (Aindex + i); Abcdefghijklmnopqrxtuvwxyz "; var digits = buildstring (10,function (i) {return i;}) digits;//"0123456789"-var random = buildstring (9,function () {     random + = String.fromCharCode (Math.floor ( Math.random () *26) +aindex19}); random;//"Yefjmcef" (random)

This gives the reader a clearer idea of what the code can do without needing to delve into the details.

Note

JavaScript returns the formula for a specified range of random numbers (between m-n): Math.random () * (N-M) +m

Also pay attention to the requirements of the topic, whether to return a positive integer

2.3 Calling Pattern

Calling a function pauses the execution of the current function, passing control and parameters to the new function. In addition to the formal parameters defined at the time of declaration, each function receives two new additional parameters: this and arguments.

This is a very important parameter, and its value is determined by the invocation pattern.

Here are the 4 calling patterns that are important in javascript:

A. Method invocation pattern the invocation pattern

B. function call pattern the functions invocation pattern

C. constructor invocation pattern the constructor invocation pattern

D. Apply call mode the Apply invocation pattern

These patterns differ on how to initialize the key parameter of this


1. Method call mode the methods invocation method

When a function is a method of an object, we call the function the method. When a method is called, this binds to the called object.

var myobj={    val:0,    Increment:function (inc) {         this.val+=typeof inc = = = "Number"?    inc:1;    },    get_val:function () {return this.val;}} Myobj.increment ();//1myobj["increment"] (2);//3    

Summary:

1. The method by which the context of the object to which they belong is called a public method

2. When using a. or subscript expression to use a function, it is the method invocation pattern, the This object is bound to the preceding object.

3, a function can use this to access an object, so it can retrieve the value of an object or change the value of an object. Bind this to an object that occurs at the time of the call.

2. Function call mode the functions invocation pattern

When a function is not a property of an object, it is called as a function. This is bound to a global object when a function is called as a function call pattern. This is a JavaScript design error and continues.

function add (x, y) {return x+y;} Myobj.double=function () {    var that=this;    var helper=function () {        that.val=add (that.value,that.value);        The wrong way of writing may be, why is it wrong? Because the function is called as an intrinsic function, this is already bound to the wrong object, and the global object does not have a Val attribute, so it returns an incorrect value.          //this.val = This.val+this.val; } helper ();} Myobj.double ();//6        

3. Constructor invocation mode the constructor invocation pattern

JavaScript is a prototype-based language, which means that objects can inherit properties from other objects directly, and that language is classless.

If you call with new in front of a function, you will get a new object that hides the prototype member connected to the function, and this will also bind to the new object.

The new prefix also alters the behavior of the return statement. This is not a recommended programming method either.

var Foo = function (status) {    this.status = status;} Foo.prototype.get_status = function () {    return this.status;} Constructs an instance of Foo var myfoo = new Foo ("Bar"); Myfoo.get_status ();//"Bar"

4. Apply call mode the Apply invocation pattern

Because JavaScript is a functional object-oriented language, functions can have methods.

The Apply method has two parameters, the first is the value to bind to this, the second is the parameter array, that is, the Apply method lets us construct an array and use it to invoke the function, which allows us to select the value of this and allows us to select the value of the array.

var array = [3,4];var sum = add.apply (Null,array); 7var statusobj = {status: "ABCDEFG"}; Foo.prototype.pro_get_status = function (prefix) {    return prefix + "-" +this.status;} var status = Foo.prototype.get_status.apply (statusobj);//"ABCDEFG" var pro_status = Foo.prototype.get_status.apply ( statusobj,["prefix"]);//"PREFIX-ABCDEFG"

Typically, the recipient of a function or method (the value of the class binding to the Special keyword this) is determined by the caller's syntax. In particular, the method invocation syntax binds a method to the Lookup object to the this variable. However, it is sometimes necessary to invoke a function using a custom receiver. You need to use the call method or the Bind method to customize the receiver to invoke the method

2.4 Using the Bind method to extract a method with a definite recipient

Because the methods and values are not different from the properties of the function, it is also easy to extract the object's methods and extract the function as a callback function directly to the higher order function.

But it's also easy to forget to bind the extracted function to the object that the function was extracted from.

var buffer = {     entries: [],     add:function (s) {         this.entries.push (s);     }    }
var Source = ["867", "-", "5309"];source.foreach (Butter.add);//error:entries is undefined

The recipient of the Butter.add at this time is not butter object. The receiver of the function depends on how it is called, and the Foreach method is called in the global scope, so the implementation of the Foreach method uses the global object as the default recipient, because there is no entries attribute in the Global object, so this code throws an error.

The Foreach method allows the caller to provide an optional parameter as the recipient of the callback function.

var Source = ["867", "-", "5309"];source.foreach (Butter.add,butter);

But not all high-order functions are attentive to the recipient of the callback function provided by the user.

There are two ways to resolve this:

1) Create an explicit buffer object method to invoke the Add wrapper function. Regardless of how the encapsulated function is called, it always ensures that its arguments are pushed into the target array.

var Source = ["867", "-", "5309"];source.foreach (function (s) {    butter.add (s);});

2) The Bind method of the function object requires a recipient object and produces a wrapper function that invokes the original function in a method called by the method of the recipient object.

var Source = ["867", "-", "5309"];source.foreach (butter.add.bind (buffer));

Note

Buffer.add.bind (buffer) creates a new function instead of modifying the Buffer.add function:

Buffer.add = = = Buffer.add.bind (buffer); False

Write high-quality JS code in

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.