function test() { var num = 1; if (true) { num = 2; alert(num); // 2 } alert(num); // 2 }
var scope="global"; function t(){ console.log(scope); // undefined,變量提高 var scope="local" console.log(scope); // local } t();
function Test() { var a = 1; this.b = 1; this.show = function() { alert('a=' + a); alert('b=' + this.b); } this.setValue = function() { a = 2; this.b++; } } var obj1 = new Test(); obj1.show(); // a=1,b=1; var obj2 = new Test(); obj2.setValue(); obj2.show(); // a=2,b=2; obj1.show(); // a=1,b=1; 上面的實例中,a是構造函數內部的一個變量,咱們在實例化obj1和obj2以後,發如今實例化對象時,obj1和obj2各有一個做用域,其中的a並非一份,而是不一樣的值。相互之間的操做並不影響。這裏的a至關於私有變量,對於每個對象來說,也都是不一樣的。
(function() { var privateStatic = "privatestatic"; Func = function() { this.setPrivateStatic = function(value) { privateStatic = value; } this.getPrivateStatic = function() { return privateStatic; } } })(); var func1 = new Func(); var func2 = new Func(); console.log(func1.getPrivateStatic()); // privatestatic console.log(func2.getPrivateStatic()); // privatestatic console.log(func1.setPrivateStatic('changed')); console.log(func2.getPrivateStatic()); //changed
(function b() { var c = 1; a(); // c is not defined })() function d() { var c = 2; console.log(c); }; (function b() { var c = 1; d(); // 2 })()
https://www.cnblogs.com/dolph...
http://www.cnblogs.com/dolphi...
https://www.cnblogs.com/lhb25...
http://www.cnblogs.com/zxj159...
https://www.cnblogs.com/syfwh...
https://www.cnblogs.com/myyou...javascript