• Blogs (9)
    • šŸ“± 236 - 992 - 3846

      šŸ“§ jxjwilliam@gmail.com

    • Version: ā€šŸš€ 1.1.0
  • JavaScript: closure and 'this' object

    Blogs20142014-04-13


    JavaScript: closure and ā€˜this’ object

    How to use ā€˜this’ object in closure function? The following is an example:

    var name  = "Window Variable";
    var obj = {
    	name : 'Object Property',
    	getName: function() {
    		return function() {
    			return this.name;
    		};
    	}
    };
    obj.getName()();   // "Window Variable"
    // The above is not correct, coz in getName() there is no 'name'
    // property, so extend to Global variable 'name'.
    
    // 2. use call(), apply() to use 'obj' instead of 'window':
    obj.getName().apply(obj);  // "Object Property"
    obj.getName().call(obj);  // "Object Property"
    
    // 3. And use intermediate variable 'that' to remain
    // it is accessible in the function range:
    var obj1 = {
    	name : 'Object Property',
    	getName: function() {
    		var that = this;
    		return function() {
    			return that.name;
    		};
    	}
    };
    obj1.getName()() //"Object Property"