简体   繁体   English

为什么javascript静态变量在不创建最少一个实例的情况下不能访问(使用类名)?

[英]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.

相关问题 在不使用类实例的情况下访问javascript类的静态属性 - Access the static property of a javascript class without using an instance of the class 无法使用静态方法返回的类实例访问类方法 - not able to access class methods using the class instance returned by a static method 在JavaScript中使用相同的变量名创建新实例 - Creating new instance with same variable name in Javascript 是否可以从类实例中在Javascript中重新分配静态类变量? - Is it possible to REassign a static class variable in Javascript from within a class instance? 我可以在不使用名称的情况下引用 class 的 static 变量吗? (用于继承) - Can I refer to a static variable of a class without using its name? (for inheritance) 在另一个文件中创建一个 class 的实例而不创建新变量 - Make an instance of a class that is in an another file without creating a new variable 在 JavaScript 中创建只有抽象 class 可以访问的 static 方法 - Creating static methods that only the abstract class can access in JavaScript Javascript中的访问实例变量 - Access Instance variable in Javascript 从javascript中类组件之一的事件侦听器访问类的实例 - Access an instance of a class from an event listener of one of the class components in javascript 在 JavaScript 中创建新对象实例而不覆盖旧对象实例 - Creating new object instance without overwriting the old one in JavaScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM