Home >Web Front-end >JS Tutorial >How to define static methods in JavaScript
In JavaScript, methods and properties defined directly on the constructor are static, while methods and properties defined on the prototype and instance of the constructor are non-static. Static methods are mainly used to operate static properties and can be defined with "class name.property=function(){}".
The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, Dell G3 computer.
function ClassA(){ //定义构造函数 }; ClassA.func = function(){ //在构造函数上添加一个属性(因为函数也是对象) console.log("This is a static method"); } var instance = new ClassA(); //新建一个实例 ClassA.func(); //This is a static method instance.func(); //Error:instance.func is not a function
When a function is defined and the attributes and functions added by "." are still accessible through the object itself, but its instances cannot be accessed, such variables and functions are called static. variables and static functions.
function Obj(){ } Obj.a=0; //静态变量 Obj.fn=function(){ //静态函数 } console.log(Obj.a); //0 console.log(typeof Obj.fn); //function var o=new Obj(); console.log(o.a); //undefined console.log(typeof o.fn); //undefined
Static methods cannot be called by instance objects, and instance methods cannot be called by constructed objects.
Recommended learning: javascript video tutorial
The above is the detailed content of How to define static methods in JavaScript. For more information, please follow other related articles on the PHP Chinese website!