Difficult points in JavaScript

Source: Internet
Author: User
Tags array definition closure garbage collection

I wrote JavaScript for a year or two, but there were a couple of ambiguous points that bothered me. Then use the most recent spare time to digest these points.

1 The scope of JavaScript

The scope in JavaScript only has one--public scope. All the properties and methods of all objects in JavaScript are public.

JavaScript also has no static scope. However, it can provide properties and methods to the constructor. constructors are just functions. Functions are objects, and objects can have properties and methods.

JavaScript standards specify the order in which type attributes are found: First, on the type's instance, and if not, continue to look up on the type prototype, which uses a short-circuit algorithm that finds its first return.

The JavaScript language is unique to the chain scope structure (chain scope), where child objects look up the variables of all the parent objects at a level. All the variables of the parent object are visible to the child, but not to the opposite.

if (true) {
	var val = ' Hello world! ';
}
Console.log (Val); Output Hello world!
View the above code in languages such as Java or C + +, this is not legal, but in JavaScript it is fully supported. The scope of JavaScript is entirely determined by functions, not blocks. For example

var val = ' Hello world! ';
function scope () {
	console.log (val);//Output undefinded
	var val = ' Hello javascript! ';
}
Scope ();

For other languages, it should be output Hello world!, but the result is incredible. This is the problem with JavaScript's type attribute lookup order. The first query is whether Val is defined within the scope () function, and if so, the Val in the upper scope will be masked. So in the execution of Console.log, Val is actually undefined. Let's look at a more complicated example

var closure = function () {
	var scope = ' scope1 ';
	(function () {
		var scope = ' scope1 ';
		(function () {
			console.log (scope);//output undefined
			var scope = ' scope2 ';
			(function () {
				console.log (scope);//Output Scope2
			}) ();
		}) ();
	}) ();
};
Closure ();

2 "Closure

According to the concept of a chain scope, this is not possible if I want to refer to variables inside the function outside of the function. But we can improve the way some functions are implemented, such as

function outer () {
	var i=0;
	function inner () {
		console.log ("first" + ++i +) secondary execution. ");
	}
	return inner;
}
var result = outer ();
Result ();//1th time execution. Result
();//2nd time execution. Result
();//3rd time execution.

Or

var outer = null;
(function () {
    var i = 0;
    function inner () {
        console.log (++i);
    }
    outer = inner;
}) ();
Outer ();    1
outer ();    2
outer ();    3
The variable result outside the outer can refer to the inner function within the outer, and the inner is the closure, which is a function inside the function that connects the function inside and outside the function.

The closure has three important functions, in the above example, result can read the outer internal variable I, this is his first role, the second function is to store variables, so that the value of the variable can always stay in memory. For example, the value of I is not released after the first result is executed, so I will add 1 after each execution. The reason for this is that the garbage collection mechanism GC does not reclaim the memory outer I occupy after outer execution, because inner execution also relies on the outer variable I; the third effect is the proprietary and encapsulation of the manufacturing class member, such as jquery, Prototype, such as JS Framework is the use of closures. So that the outside world will not destroy the framework inside the frame. For example

function Closure () {  
    var id;  
    This.getid = function () {return  
        ID;  
    }  
    This.setid = function (nid) {  
        id = nid;  
    }}  
var c = new Closure ();  
C.setid (1);  
Console.log (C.getid ()); 1
The external ID is inaccessible, and you can set the value using a setter method and get it in a getter way, which is somewhat java,c/c++ in the meaning of high-level language encapsulation.

A serious problem with closures is that they can easily lead to memory leaks. In general, the GC is automatically used when the object is useless, but it is not released when the JavaScript object appears as a circular reference. For example, three object ABC, their reference relationship is as follows: This adds a property of C to refer to B object, if this is clear a, then B, C will not be released, because a circular reference between B and C a->b->c->b. And closures are a kind of covert circular reference.

3 "Call and apply"

The function of call and apply is to invoke a function with a different object as the context. In short, one object is allowed to invoke the member function of another object.

1. Each function contains two methods that are not inherited: Apply () and call ().
2, they are used the same, are in a specific scope of the call function.
3, receive parameters, apply () receive two parameters, one is the scope of the function run (this), the other is a parameter array.
The first parameter of the call () method is the same as the Apply () method, but the arguments passed to the function must be enumerated. Apply is passed in a parameter array, which is the combination of multiple arguments into an array, while call is passed as a call parameter (starting with the second argument), and if no thisobj argument is supplied, the Global object is used as a thisobj. such as Func.call (FUNC1,VAR1,VAR2,VAR3) corresponding apply is written as: Func.apply (FUNC1,[VAR1,VAR2,VAR3)). Here is an example of a class student that does not have a display method that has the display method of the user class.

function User (Name,age)
{
	this.name = name;
	This.age = age;
	This.display = function () {
		console.log ("I ' m" + name + ", I ' M" + age);
	}
}
function Student (name,age) {
	//user.apply (this,arguments);
	User.call (this,name,age);
}
var s = new Student ("Fly", num);
S.display ();//i ' m fly,i ' m 26
Through the example above, we find that apply and call can implement class inheritance. And this way in the ExtJS inside the application is very much. In ExtJS, there is a applyif, which is a little different from apply, for example, if the name attribute is already included in student, the name attribute in user will not be copied.

Apply the most magical use of the array aspect. Look at the example below

var arr = [5,6,1,3,7];
Console.log (Math.max (5,6,1,3,7)); 7
Console.log (Math.max (arr));//nan
Console.log (Math.max.apply (0,arr));//7
In the JS built-in math object has already implemented the array contrast, but is the parameter way to pass the value, passes the array directly to be able to appear the error. If you have to do this, you must rewrite the Max method, but we have to apply this artifact to simply solve the problem. Since the first parameter must be present, we can pass any parameter instead of the scope. Includes global, numeric, or null.
4 "bind"

How to change the context of the called function. As I said before, you can use the call or Apply method, but it's inconvenient if you reuse it because you pass the context object as a parameter each time, and it makes the code less intuitive. In this case, we can use the Bind method to permanently bind the context of the function so that the context is fixed regardless of who invoked it. Here's a look at the example program on MSDN:

var originalobject = {
    minimum:50,
    maximum:100,
    checknumericrange:function (value) {
        if (typeof value !== ' number ') return
            false;
        else return
            value >= this.minimum && value <= this.maximum;
    }
Console.log (Originalobject.checknumericrange);//false
var range = {minimum:10, maximum:20};
var boundobjectwithrange = originalObject.checkNumericRange.bind (range);
Console.log (boundobjectwithrange);//true
This is the first role of BIND, which modifies the this pointer when the function is called. When Boundobjectwithrange calls, the Bind method is used, and the this pointer points to a Range object. Let's look at the example of passing parameters:

var Displayargs = function (Val1, Val2, Val3, Val4) {
    Console.log (val1 + "" + Val2 + "" + Val3 + "" + Val4);
}
var emptyobject = {};
var displayArgs2 = Displayargs.bind (Emptyobject, "a");
DISPLAYARGS2 ("B", "C"); A b C

Note Two for bind: This will not be modified when you invoke the new function created by bind using the the new operator, but the parameters are modified, and bind is not supported by all browsers, IE is not currently supported.

5 "prototype prototype

First look at an example program, which I used in the project. Gets the index value of an element in the array, and there is no such method in the default array definition.

Array.prototype.getIndexByValue = function (value)
{
	var index =-1;
	for (var i = 0; i < this.length i++)
	{
		if (this[i] = = value)
		{
			index = i;
			break;
		}
	}
	return index;
};
Console.log ([2,3,4,6,8].getindexbyvalue (6)); 3
Prototype the class of the object returns a reference to the prototype. Each class has a prototype instance. We can use Proptotype on the type to add behavior to the type. These behaviors can only be represented on instances of a type.
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.