• Blogs (9)
    • 📱 236 - 992 - 3846

      📧 jxjwilliam@gmail.com

    • Version: ‍🚀 1.1.0
  • JavaScript: closure, local variable, and call

    Blogs20132013-06-24


    JavaScript: closure, local variable, and call

    The follow JavaScript codes have 3 features:

    1. It is a Closure.
    2. It uses var _this=this; to define a local variable (using var, so not a global variable)
    3. It uses call() to control the calling range
    var name = "The Window";
    
    var object = {
      name : "My Object",
    
      getNameFunc : function(){
        var _this = this;
      return function(){
        return _this.name + '___' + this.name;
      };
      }
    };
    
    console.log(object.getNameFunc()());
    console.log(object.getNameFunc.call(object)());
    console.log(object.getNameFunc.call(window)());
    console.log(object.getNameFunc.call(undefined)());
    console.log(object.getNameFunc.call(document.window)());
    console.log(object.getNameFunc.call(this)());

    The returns:

    My Object___The Window My Object___The Window The Window___The Window The Window___The Window The Window___The Window The Window___The Window