JS Closed Package

Source: Internet
Author: User
Tags variable scope

Closure-caused bugs
function bug () {
var nums = [];
for (var i = 0; i < 3; i++) {
Nums[i] = function () {
return i;
};
}
return nums;
}
var nums_bug = bug ();
Console.log (Nums_bug[0] ());
Console.log (Nums_bug[1] ());
Console.log (Nums_bug[2] ());
Fix bugs
function Fbug () {
var nums = [];
for (var i = 0; i < 3; i++) {
Nums[i] = (function (i) {
return i;
}) (i);
}
return nums;
}
var nums = Fbug ();
Console.log (Nums);
Nums[0] (); 0
NUMS[1] (); 1
NUMS[2] (); 2

Isolation variable Scope
(function () {
var name = "Zs";
function A () {
name = ' SSS ';
}
})();
(function () {
var name = "ls";
function A () {
name = ' VVV ';
}
})();

Counter
Common implementation
var num = 0;
function Countnum () {
num + +;
}
Countnum ();
Console.log (num);
Closure implementation
var counter = (function () {
var counterper = 0;
return function () {
return counterper++;
}
})();
Console.log (counter ());

var counter= (function () {
Assigning an initial value
var count=0;
The closure is formed when externally called
return function () {
return count++;
}
})();
Declaring private variables

/*function people () {
THIS.name = ' Zhang San ';
}
var p = new people ();
Console.log (p.name); * *
Directly can. To access, which is the public attribute, the security is poor
The private property is passed through the. Unreachable

var people = (function () {
var name = ';
function people () {

}
People.prototype = {
Getname:function () {
return name;
},
Setname:function (newName) {
name = NewName;
}
}
return people;
})();
var p = new people ();

This
var test = ' John Doe ';
function Th_test () {
Console.log (this.test);
}

function Bth_test () {
var test = ' Harry ';
return function () {
Console.log (this.test);
}
}
This always points to the object that called it

JS Closed Package

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.