[英]Why javascript static variable not able to access ( using class name ) without creating minimum one instance?
I am creating one function like below 我正在创建一个像下面的功能
function calculation(){
this.add=function(x,y){
return x+y;
}
calculation.sub=function(x,y){
return x-y; //static method
};
function mul(x,y){
return x*y; //static method
}
calculation.mul=mul;
}
after declaration of this method, if call like this calculation.mul(2,1)
I am getting an error like. 声明此方法后,如果像这样进行
calculation.mul(2,1)
调用calculation.mul(2,1)
我收到类似错误。
VM3676:1 Uncaught TypeError: calculation.mul is not a function at :1:13
VM3676:1未被捕获的TypeError:Calculation.mul不是位于1:1:13的函数
But, var _calc=new calculation();
但是,
var _calc=new calculation();
after creation of instance, I am able to access the static method. 创建实例后,我可以访问静态方法。
calculation.mul(2,1) if i try after this, i am getting value `2`.
Anyone, please clarify me. 有人请澄清一下 Thanks, advance.
谢谢,提前。
Because the code which assigns the mul
property to the calculation
object: 因为将
mul
属性分配给calculation
对象的代码为:
calculation.mul=mul;
… is inside the calculation
function. … 在
calculation
功能内。 Therefore it only runs when you call the calculation
function. 因此,它仅在调用
calculation
功能时运行。
Move it outside if you don't want it to work that way. 如果您不希望它那样工作,请将其移到外面。
function calculation() { this.add = function(x, y) { return x + y; } calculation.sub = function(x, y) { return x - y; //static method }; } function mul(x, y) { return x * y; //static method } calculation.mul = mul; console.log(calculation.mul(2, 1))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.