如何在Javascript中创建静态变量?
当前回答
在JavaScript中,任何东西都是原始类型或对象。函数是对象-(键值对)。
创建函数时,将创建两个对象。一个对象表示函数本身,另一个对象代表函数的原型。
从这个意义上讲,函数基本上是一个具有财产的对象:
function name,
arguments length
and the functional prototype.
因此,在何处设置静态属性:两个位置,要么在函数对象内部,要么在功能原型对象内部。
这里有一个代码片段,它使用新的JavaScript关键字创建了两个实例。
函数C(){//函数var privateProperty=“42”;this.publicProperty=“39”;this.privateMethod=函数(){console.log(privateProperty);};}C.prototype.publicMethod=函数(){console.log(this.publicProperty);};C.prototype.staticPrototypeProperty=“4”;C.staticProperty=“3”;var i1=新C();//实例1var i2=新C();//实例2i1.privateMethod();i1.publicMethod();console.log(i1.__proto__.staticPrototypeProperty);i1.__proto__.staticPrototypeProperty=“2”;console.log(i2.__proto__.staticPrototypeProperty);console.log(i1.__proto__constructor.staticProperty);i1.__proto__constructor.staticProperty=“9”;console.log(i2.__proto__constructor.staticProperty);
主要思想是实例i1和i2使用相同的静态财产。
其他回答
function Person(){
if(Person.count == undefined){
Person.count = 1;
}
else{
Person.count ++;
}
console.log(Person.count);
}
var p1 = new Person();
var p2 = new Person();
var p3 = new Person();
如果要创建全局静态变量:
var my_id = 123;
将变量替换为以下内容:
Object.defineProperty(window, 'my_id', {
get: function() {
return 123;
},
configurable : false,
enumerable : false
});
在JavaScript中,任何东西都是原始类型或对象。函数是对象-(键值对)。
创建函数时,将创建两个对象。一个对象表示函数本身,另一个对象代表函数的原型。
从这个意义上讲,函数基本上是一个具有财产的对象:
function name,
arguments length
and the functional prototype.
因此,在何处设置静态属性:两个位置,要么在函数对象内部,要么在功能原型对象内部。
这里有一个代码片段,它使用新的JavaScript关键字创建了两个实例。
函数C(){//函数var privateProperty=“42”;this.publicProperty=“39”;this.privateMethod=函数(){console.log(privateProperty);};}C.prototype.publicMethod=函数(){console.log(this.publicProperty);};C.prototype.staticPrototypeProperty=“4”;C.staticProperty=“3”;var i1=新C();//实例1var i2=新C();//实例2i1.privateMethod();i1.publicMethod();console.log(i1.__proto__.staticPrototypeProperty);i1.__proto__.staticPrototypeProperty=“2”;console.log(i2.__proto__.staticPrototypeProperty);console.log(i1.__proto__constructor.staticProperty);i1.__proto__constructor.staticProperty=“9”;console.log(i2.__proto__constructor.staticProperty);
主要思想是实例i1和i2使用相同的静态财产。
在JavaScript中,没有静态的术语或关键字,但我们可以将这些数据直接放到函数对象中(就像在任何其他对象中一样)。
function f() {
f.count = ++f.count || 1 // f.count is undefined at first
alert("Call No " + f.count)
}
f(); // Call No 1
f(); // Call No 2
我通常使用这种方法有两个主要原因:
如果我想存储函数的本地值,我会使用“local.x”、“local.y”、“local.TempData”等。。。!
如果我想存储函数的静态值,我会使用“static.o”、“static.Info”、“static.count”等。。。!
[Update2]:方法相同,但使用IIFE方法!
[Update1]:通过预编辑脚本自动创建函数的“静态”和“本地”对象!