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/

  • 相关阅读:
    c++ 有序二叉树的应用
    c++ 二叉树的遍历
    c++ 创建二叉树
    c++ 双向链表 的查找和删除
    c++ 双向循环链表
    c++ 双向链表
    Jzoj4209 已经没有什么好害怕的了
    Jzoj4209 已经没有什么好害怕的了
    后缀自动机转后缀树模板
    后缀自动机转后缀树模板
  • 原文地址:https://www.cnblogs.com/voctrals/p/3706618.html
Copyright © 2011-2022 走看看