zoukankan      html  css  js  c++  java
  • 关于JavaScript变量的Scope

    1 var sth = ""; // Global Scope

    2 var foo = function(){

      var sth = ""; // Local Scope

    }

    3 var foo = function(){

      sth = ""; // Global Scope, this is definitely denied!

    }

    4 (function(){

      var jQuery = {

        // variable methods or definitions  

      }

      window.jQuery = jQuery;

    })(); // Immediately-Invoked Function Expressions, This is used by jQuery and some other liberaries.

    point1: the var exsits in var jQuery is very important, without it jQuery will be global scope.

    point2: though the jQuery is also global scope, but when another jQuery defined in window, it will also work.

    according to http://learn.jquery.com/javascript-101/scope/

    5 closure

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

      setTimeOut(function(){

        alert(i);  // will not alert correctly~, because the i has already added for 5 times in the fiven 1000 mill-seconds.

      }, 1000);

    }

    to correct this, we should use closure.

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

      setTimeOut(alertFunc(i), i*1000); // why? the function will be called immediately with parameter i, so the alertFunc knows that i, and only i nothing else, then alert 0, 1, 2, 3, 4, end~

    }

    var alertFunc = function(i){

      alert(i);

    }

    according to http://learn.jquery.com/javascript-101/closures/

  • 相关阅读:
    java学习day08--面向对象--继承+方法重写+static关键字
    java学习day07--面向对象--封装+this关键字+构造器
    java学习day06-面向对象--类和对象
    依赖管理
    NSQ消息队列
    logger包
    time包
    fmt包
    Go_Protobu
    Go_性能优化
  • 原文地址:https://www.cnblogs.com/voctrals/p/3706618.html
Copyright © 2011-2022 走看看