How to Write high-quality JS Code (continued) and high-quality js Code

Source: Internet
Author: User

How to Write high-quality JS Code (continued) and high-quality js Code

Continue with the previous article "How to Write high-quality JS Code" to sort out javascript function knowledge points this time.

2. Use Functions

Functions provide major Abstract Functions and implementation mechanisms for programmers. Functions can independently implement multiple different features in other languages, such as processes, methods, constructors, and even classes or modules.

2.1 understand the differences between function calls, method calls, and constructor calls

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

Usage mode:

1. function call

Copy codeThe Code is as follows:
Function hello (username ){
Return "hello" + username;
}

2. method call

Copy codeThe Code is as follows:
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. We can assign the same function reference to another object and get the same answer.

Copy codeThe Code is as follows:
Var obj2 = {
Hello: obj. hello (),
Username: "floraLam"
};

3. Use constructors

Copy codeThe Code is as follows:
Function User (name, passwordHash ){
This. name = name;
This. passwordHash = passwordHash;
}

Calling a User using the new operator is considered a constructor.

Copy codeThe Code is as follows:
Var u = new User ("floraLam", "123 ");

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

2.2 master advanced functions

A high-order function is nothing more than a function that uses a function as a parameter or a return value, and uses a function as a parameter (usually called a callback function, because a high-order function "then calls" it) it is a very powerful and expressive usage and is also widely used in js programs.

Consider the standard sort method of arrays. To work on all arrays, the sort method requires the caller to determine how to compare any two elements in the array.

Copy codeThe Code is as follows:
Function compareNumber (x, y ){
If (x <y ){
Return-1;
}
If (x> y ){
Return 1;
}
Return 0;
}
[,]. Sort (compareNumbers); // [,]

Copy codeThe Code is as follows:
[3, 1, 4, 1, 5, 9]. sort (function (x, y ){
If (x <y ){
Return-1;
}
If (x> y ){
Return 1;
}
Return 0;
}); // [1, 1, 3, 4, 5, 9]

The preceding example uses an anonymous function to further simplify the process.

Learning to use higher-order functions can simplify code and eliminate tedious sample code. We can use loops to convert string Arrays:

Copy codeThe Code is as follows:
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"];

The convenient map Method of arrays can eliminate loops. Only one local function can be used to convert elements one by one.

Copy codeThe Code is as follows:
Var names = ["Fred", "Wilma", "Pebbles"];
Var upper = names. map (function (name ){
Return name. toUpperCase ();
});
Upper; // ["FRED", "WILMA", "PEBBLES"];

In addition, for example, we want to create several methods to create different strings with the same implementation logic. Each loop creates a string by connecting the computing results of each independent part.

Copy codeThe Code is as follows:
Function bucket string (n, callback ){
Var result = "";
For (var I = 0; I <n; I ++ ){
Result + = callback (I );
}
Return result;
}
Var alphabet = bucket string (26, function (I ){
Return String. fromCharCode (aIndex + I );
});
Alphabet; // "abcdefghijklmnopqrxtuvwxyz ";
Var digits = buildString (10, function (I) {return I ;})
Digits; // "0123456789"
Var random = buildString (9, function (){
Random + = String. fromCharCode (Math. floor (Math. random () * 26) + aIndex
});
Random; // "yefjmcef" (random)

This gives readers a clearer understanding of what the code can do without in-depth implementation details.

Remarks

Javascript returns the formula of a random number (between m-n) in the specified range: Math. random () * (n-m) + m

At the same time, pay attention to the question requirements, whether to return a positive integer

2.3 call mode

When a function is called, the execution of the current function is suspended, and control and parameters are passed to the new function. In addition to the formal parameters defined during declaration, each function receives two new additional parameters: this and arguments.

This is a very important parameter and its value is determined by the call mode.

The following four call modes are important in JavaScript:

A. method call mode the method invocation pattern
B. function call mode: the function invocation pattern
C. constructor invocation pattern
D. Apply call mode the apply invocation pattern

These modes differ in how key parameters such as this are initialized.

1. method call mode the method invocation method

When a function acts as an object method, we call it a method. When a method is called, this is bound to the called object.

Copy codeThe Code is as follows:
Var myObj = {
Val: 0,
Increment: function (inc ){
This. val + = typeof inc = "number "? Inc: 1;
},
Get_val: function () {return this. val ;}
}
MyObj. increment (); // 1
MyObj ["increment"] (2); // 3

Summary:

1. the method that uses this to obtain the context of the object to which they belong is called a public method.

2. When a function is used using a. Or subscript expression, it is the method call mode. this object is bound to the previous object.

3. A function can use this to access an object, so it can retrieve or change the value of an object. Binding this to an object occurs during the call.

2. function call mode the function invocation pattern

When a function is not an object attribute, it is called as a function. When a function is called as a function call mode, this is bound to a global object. This is a JavaScript design error and continues.

Copy codeThe Code is as follows:
Function add (x, y ){
Return x + y;
}
MyObj. double = function (){
Var that = this;
Var helper = function (){
That. val = add (that. value, that. value );
// The incorrect writing method may be like this. Why is it wrong? When a function is called as an internal function, this has been bound to an incorrect object, and the global object does not have the val attribute. Therefore, an incorrect value is returned.
// This. val = this. val + this. val;
}
Helper ();
}
MyObj. double (); // 6

3. constructor invocation pattern

JavaScript is a prototype-based inherited language, which means that an object can directly inherit attributes from other objects.

If a function is called with new in front of it, a new object hidden from the prototype member connected to the function will be obtained, and this will be bound to the new object.

The new prefix also changes the behavior of the return Statement. This is not the recommended programming method.

Copy codeThe Code is as follows:
Var Foo = function (status ){
This. status = status;
}
Foo. prototype. get_status = function (){
Return this. status;
}
// Construct a Foo instance
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 bound to this, and the second is the parameter array. That is to say, the Apply method allows us to construct an array and use it to call the function, this allows us to select the value of this and the value of the array.

Copy codeThe Code is as follows:
Var array = [3, 4];
Var sum = add. apply (null, array); // 7
Var 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"

In general, the receiver of a function or method (the value that is bound to the special keyword this) is determined by the caller's syntax. In particular, the method call syntax binds the method object to the this variable. However, you sometimes need to use a custom receiver to call a function. In this case, you need to use the call method or bind method to customize the receiver to call the method.

2.4 use the bind method to extract methods with a definite Receiver

Since there is no difference between the method and the attribute whose value is a function, It is also easy to extract the object method and extract the function as a callback function and pass it directly to the higher-order function.

However, it is easy to forget to bind the extracted function to the extracted object.

Copy codeThe Code is as follows:
Var buffer = {
Entries: [],
Add: function (s ){
This. entries. push (s );
}
}
Var source = ["867", "-", "5309"];
Source. forEach (butter. add); // error: entries is undefined

In this case, the receiver of butter. add is not a butter object. The receiver of the function depends on how it is called. The forEach method is called in the global scope. Therefore, the implementation of the forEach method uses the Global object as the default receiver, this code throws an error because the global object does not have the entries attribute.

The forEach method allows the caller to provide an optional parameter as the receiver of the callback function.

Copy codeThe Code is as follows:
Var source = ["867", "-", "5309"];
Source. forEach (butter. add, butter );

However, not all higher-order functions are attentive to providing users with the receiver of the callback function.

There are two solutions:

1) Create an explicit buffer object method to call the add encapsulation function. No matter how the encapsulated function is called, it always pushes its parameters to the target array.

Copy codeThe Code is as follows:
Var source = ["867", "-", "5309"];
Source. forEach (function (s ){
Butter. add (s );
});

2) The bind method of the function object requires a receiver object and generates a method called by the method of the receiver object to call the encapsulated function of the original function.

Copy codeThe Code is as follows:
Var source = ["867", "-", "5309"];
Source. forEach (butter. add. bind (buffer ));

Remarks

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

Buffer. add = buffer. add. bind (buffer); // false

The above is all the content of this article. I hope you will like it.

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.