JavaScript Deep Learning

Source: Internet
Author: User

1. JavaScript scope principle

var name = ' Laruence ';
function echo () {
alert (name); Laruence
var name = ' Eve ';
alert (name); Eve
alert (age); Script error
}

Echo ();

What is the result of the operation?

The above question, I believe many people will think that should be like comments.

Once executed, it was undefined that the first alert came out. Why is it?

The JS authoritative guide has a very incisive description: "The functions in JavaScript run in their defined scopes, not in the scopes they are executed in."

In fact, in JS: "Everything is the object, function is also."

When a function is defined, the scope chain that defines the moment is linked to the [scope] property of the function object.
When a function object is called, an active object (that is, an object) is created, and then, for each function's formal parameter, it is named as the active object's named property, then the active object is the front-end of the scope chain (scope chain) at this time, and this function object's [[ Scope]] added to scope chain.

Look at an example:

    1.      var func = function{
    2.            var name = Laruence '
    3.            ...
    4.      }
    5.      func ();

When the func is called, an active object is created (assumed to be aobj, created by the JS engine precompiled moment, described later), and the Arguments property is created, and then the object is added with two named properties Aobj.lps, Aobj.rps;

For each local variable and function definition declared in this function, it is named as the Name property of the active object.

With the above scope chain, in the event of identifier parsing, the property of each active object of the current scope chain list is queried backwards, and returned if the same name is found. Not found, that is, the identifier is not defined.

Notice that because the [scope] property of a function object is determined when a function is defined, not when it is called, as in the following example:

  1. Function Factory() {
  2. var name = ' laruence ';
  3. var intro = function(){
  4. Alert(' I am ' + name);
  5. }
  6. return intro;
  7. }
  8. function app(para){
  9. var name = para;
  10. var func = factory();
  11. func();
  12. }
  13. App(' Eve ');

When the app is called, scope chain is made up of the {Window Activity Object (Global)}->{app}.

When you first enter the app function body, the app's active object has a arguments property, and the two values are undefined properties: Name and Func. and a value of ' Eve ' attribute para;

The scope chain at this time is as follows:

    1. [[Scope chain]] = [
    2. {
    3. Para : ' Eve ',
    4. Name : undefined,
    5. Func : undefined,
    6. arguments : []
    7. }, {
    8. Window Call Object
    9. }

Notice that the active object of the app is not included in the scope chain at this time.

When defining the intro function, the intro function's [[scope]] is:

      1. [[Scope chain]] = [
      2. {
      3. Name : ' laruence ',
      4. Intor : undefined
      5. }, {
      6. Window Call Object
      7. }
      8. ]

After returning from the factory function, the identifier parsing occurs when Intor is called in the app, and the Sope chain at this point is:

    1. [[scope chain]] = [
    2. {
    3.       intro Call Object
    4. } {
    5.      name ' laruence '
    6.      intor undefined
    7. }{
    8.      window Call Object
    9. }
    10. Span class= "Sh_symbol" >

Because the scope chain, the factory activity object is not included. Therefore, the result of the name identifier resolution should be the name attribute in the factory active object, which is ' laruence '.

So the result of the operation is:

I am Laruence

Now everyone is running "javascript" functions in their defined scopes, not in the scopes they are executed in. This sentence, should have a comprehensive understanding of it?

2. Prototype and prototype chain

How to use prototypes 1

varCalculator = function(decimalDigits, tax) {

  this.decimalDigits = decimalDigits;

  this.tax = tax;

};

The prototype of the Calculator object is then set by assigning a value object literal to the prototype property of the Calculator object.

Calculator.prototype = {

  add: function(x, y) {

    returnx + y;

  },

  subtract: function(x, y) {

    returnx - y;

   }

};

//alert((new Calculator()).add(1, 3));

In this way, we can call the Add method to evaluate the result after the new Calculator object.

How to use Prototypes 2

The second way is to assign a value using the expression immediately executed by the function when the value prototype prototype, that is, the following format:

Calculator.prototype = function() { } ();

Its benefits in the previous post has been known, is to encapsulate the private function, through the form of return to expose the simple use of the name to achieve public/private effect, the modified code as follows

Calculator.prototype = function() {

  add = function(x, y) {

    returnx + y;

  },

  subtract = function(x, y) {

    returnx - y;

  }

  return{

    add: add,

    subtract: subtract

  }

} ();

//alert((new Calculator()).add(11, 3));

Let's take a look at how to distribute each property of the prototype.

varBaseCalculator = function() {

  //为每个实例都声明一个小数位数

  this.decimalDigits = 2;

};

//使用原型给BaseCalculator扩展2个对象方法

BaseCalculator.prototype.add = function(x, y) {

  returnx + y;

};

BaseCalculator.prototype.subtract = function(x, y) {

  returnx - y;

};

Once you've created the above code, let's start:

varCalculator = function() {

  //为每个实例都声明一个数字

  this.tax = 5;

};

Calculator.prototype = newBaseCalculator();  

var calc = new Calculator ();
Alert (Calc.add (1, 1));
The Decimaldigits attribute declared in the Basecalculator is accessible in Calculator
alert (calc.decimaldigits);

Function Foo () {
    this.value =;
}
Foo.prototype = {
    method:function () {}
};

Function Bar () {}

//Set the prototype property of bar to an instance object of Foo
Bar.prototype = new Foo ();
Bar.prototype.foo = ' Hello world ';

//fix Bar.prototype.constructor to bar itself
Bar.prototype.constructor = bar;

var test = new Bar ()//Create a fresh instance of bar

//prototype chain
Test [instance of bar]
    Bar.prototype [instance of Foo]
& nbsp;       {foo: ' Hello World '}
        Foo.prototype
            {method: ...};
            Object.prototype
                 {toString: .../* etc. */};

Example 1: A local variable in a closure is a reference, not a copy

function say667 () {
Local variable that ends up within closure
var num = 666;
var sayalert = function () {alert (num);}
num++;
return sayalert;
}

var Sayalert = say667 ();
Sayalert ()

So the execution result should pop up 667 instead of 666.

Example 2: Multiple functions bind the same closure because they are defined within the same function.

function Setupsomeglobals () {
Local variable that ends up within closure
var num = 666;
Store some references to functions as global variables
Galertnumber = function () {alert (num);}
Gincreasenumber = function () {num++;}
Gsetnumber = function (x) {num = x;}
}
Setupsomegolbals (); Assign a value to three global variables
Galertnumber (); 666
Gincreasenumber ();
Galertnumber (); 667
Gsetnumber (12);//
Galertnumber ();//12

Example 3: When assigning functions in a loop, these functions will bind the same closures

function BuildList (list) {
var result = [];
for (var i = 0; i < list.length; i++) {
var item = ' Item ' + list[i];
Result.push (function () {alert (item + "+ List[i])});
}
return result;
}

function Testlist () {
var = buildList ([fnlist]);
Using J Prevent confusion-could use I
for (var j = 0; J < Fnlist.length; J + +) {
FNLIST[J] ();
}
}

The result of the testlist is to eject the item3 undefined window three times, because these three functions bind the same closure, and the value of item is the result of the last calculation, but when I jumps out of the loop I value is 4, so the result of list[4] is undefined.

Example 4: External function All local variables are inside the closure, even if the variable is declared after the intrinsic function definition.

function Sayalice () {
var sayalert = function () {alert (Alice);}
Local variable that ends up within closure
var alice = ' Hello Alice ';
return sayalert;
}
var helloalice=sayalice ();
Helloalice ();

The result of the execution is a window that pops up "Hello Alice". Even if a local variable is declared after the function Sayalert, the local variable can still be accessed.

Example 5: Create a new closure each time the function is called

function Newclosure (Somenum, Someref) {
Local variables that end up within closure
var num = somenum;
var = [Anarray];
var ref = Someref;
return function (x) {
num + = x;
Anarray.push (num);
Alert (' num: ' + num +
' \nanarray ' + anarray.tostring () +
' \nref.somevar ' + Ref.somevar);
}
}
Closure1=newclosure (40,{somevar: ' Closure 1 '});
Closure2=newclosure (1000,{somevar: ' Closure 2 '});

Closure1 (5); Num:45 anarray[1,2,3,45] Ref: ' Somevar closure1 '
Closure2 ( -10);//num:990 anarray[1,2,3,990] Ref: ' Somevar closure2 '

JavaScript Deep Learning

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.