JavaScript Language Essence _ Fourth Chapter

Source: Internet
Author: User

4.1 Function objects

In JavaScript, a function is an object. The object is a collection of name/value pairs and has a hidden link to the prototype object. Object literals are generated by objects connected to the Object.prototype. The function object is connected to the Function.prototype (the prototype object itself is connected to the Object.prototype)

Each function object is also accompanied by a prototype property, whose value is an object that has the constructor property and to that function

Functions can hold variables, can be passed as arguments to other functions, or they can be returned in a function.

Because a function is an object, it can be used just like any other value, or it can have a method

4.3 calls

Calling a function pauses the execution of the current function, passing control and parameters to the new function. Each function accepts two additional arguments: this and arguments.

There are four invocation patterns in JavaScript: The method invocation pattern, the function invocation pattern, the constructor invocation pattern, and the Apply invocation pattern. These patterns differ on how to initialize the key parameter this.

Method invocation Pattern

When a function is saved as a property of an object, it is called a method. The method can be accessed through this, the binding of this to the object occurs at the time of invocation, and this "super" late binding allows the function to be reused for this height.

Function call pattern

When a function is not a property of an object, it is invoked as a function (a method defined again in the object's method).

When the function is called in this mode, this is bound to the global object (this is a bug), and the method can define a variable and assign it a value of this, then the intrinsic function can access this by that variable.

constructor invocation Pattern

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

Functions that are called with the new prefix are called constructor functions, they are stored in a variable named in uppercase, and if you call the constructor function without adding new in front of you, a very bad thing can happen (error in other places, you might want to change the day ...) ), there is neither compile-time warning nor runtime warning, so the capitalization convention is important.

Apply Call pattern

Apply let's construct a parameter array and use it to invoke the function, which allows us to select the value of this. The Apply method receives two parameters, the first one is the value to bind to this, and the second is the parameter array

4.4 Parameters

When a function is called, a arguments array is obtained, which makes it possible to write a function that does not require the number of parameters to be specified.

You can construct a function that adds a number of values.

Because of this design error, arguments is not a real array, it's just an "array-like" object that has the length property, but lacks all the array methods.

4.5 return

The return statement can be used to return the function in advance. A function always returns a value and returns undefined if no return value is established.

If the function is called with a new prefix in front of it, and the return value is not an object, this is returned (the new object)

4.7 Adding methods to types

JavaScript allows you to add methods to the basic types of languages.

JavaScript does not have a separate integer type, and we can improve it by adding an integer to the Number.prototype.

Number.prototype.integer = function () {

Return Math (This < 0?) ' Ceiling ': ' floor ' [this];

}

The prototype of a primitive type is a public structure, so it is only added when you are sure that there are no changes to the method.

4.8 recursion

Recursive functions can operate the tree structure very efficiently, such as the Document Object Model (DOM) on the browser side, and handle a small segment of a given tree each time it is called recursively.

var walk_the_dom = function Walk (node,func) {

Func (node);

node = Node.firstchild;

while (node) {

Walk (Node,func);

node = node.nextsibling;

}

};

var getelementsbyattrbute = function (attr,value) {

var rusults = [];

Walk_the_dom (document.body,function (node) {

var actual = Node.nodetype = = = 1 && node.getattrbute (ATT);

if (typeof actual = = = ' String ' && (actual = = = Value | | typeof value!== ' string ')) {

Results.push (node);

}

});

return results;

};

Some languages provide tail recursion optimization, which means that if a function returns the result of its own recursive invocation, then the calling process is replaced with a loop, which can significantly increase the speed. But here JavaScript does not provide tail recursion optimizations, and deep recursive functions may fail to run because of a return stack overflow.

4.9 Scopes

JavaScript has a function scope, but no block-level scope. It is best to declare all variables that may be used in the function at the top of the function as a whole

4.10 Closures

The intrinsic function has a longer life cycle than its outside

A common example

var add_the_handlers = function (nodes) {

var i;

for (i=0; i < nodes.length; i + = 1) {

Nodes[i].onclick = function (e) {

alert (i);

}

}

};

It always shows the number of nodes because the event handler function binds the variable i, not the value of the variable I that the function constructs.

var add_the_handlers = function (nodes) {

var i;

for (i=0; i < nodes.length; i + = 1) {

Nodes[i].onclick = function (i) {

return function (e) {

alert (i);

};

} (i);

}

};

4.11 Callback

Functions can make it easier to handle discontinuous events, initiate asynchronous requests, and provide a callback function that will be called when the server's response arrives.

4.12 Modules

By using closures and functions to construct a module, a module is a function or object that provides an interface but hides state and implementation, and by using a function to generate the module, we can eliminate the use of global variables to mitigate the effects of this poor feature.

The general form of a module: a function that defines private variables and functions, the use of closures to create privileged functions that can access private variables and functions, and finally return this privileged function, or save them to an accessible place.

The module mode is typically used in a single-case mode.

4.13 Cascade

To have some methods return this instead of undefined, you can enable cascading.

In a cascade, we can sequentially invoke many methods of the same object in a single statement.

4.14 Apply

A function can be combined with the parameters passed to it to produce a new function.

4.15 Memory

In the computer field, memory is an optimization technique used primarily for accelerating program computation, and the function avoids repeating the calculation before the input has been processed, and returns the result as cached.

JavaScript objects and arrays to achieve this optimization is very convenient

var Fibonacci = function (n) {

return N < 2? N:fibonacci (n-1) + Fibonacci (n-2);

}

for (var i = 0; I <=; i + = i) {

Document.writein (i + ' = ' + Fibonacci (i));

}

This is called 11 times, and it itself calls 442 times to calculate a value that may have been just computed.

var Fibonacci = function () {

var memo = [0, 1];

var fib = function (n) {

var result = Memo[n];

if (typeof result!== ' number ') {

result = FIB (n-1) + fib (n-2);

Memo[n] = result;

}

return result;

};

return fib;

}();

This function returns the same result, calls it 11 times, and calls itself 18 times to get the result stored before it.

JavaScript Language Essence _ Fourth Chapter

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.