[Typescript] Static properties and static methods in ts

Static properties and static methods in Typescript

To use static properties and methods in ts, the static keyword is required, and only static properties can be used in static methods

give two chestnuts

in es5

function Person(){
    
    
	this.run1 = function (){
    
    } 		// 实例方法,实例化后调用
}
var p = new Person()				// 实例化
p.run1()							//调用实例方法

Person.run2 = function (){
    
    } 		// 静态方法,类名直接调用
Person.name = '哈哈哈'					// 静态属性
Person.run2() 						// 静态方法的调用,类名直接调用

in ts

class Person{
    
    
        public name:string;
        static sex = '男'   //静态属性
        constructor(name:string){
    
    
                this.name=name;
        }
        run(){
    
     //实例方法
                console.log(`${
      
      this.name}在运动`)
        }
        work(){
    
    
                console.log(`${
      
      this.name}在工作`)
        }
        static print(){
    
       //静态方法
                console.log('静态方法')   //注意这里无法直接调用类中属性,如this.name不可调用,但是可以调用静态属性Person.sex
        }
}
var d = new Person('小摆') 
d.run()   //实例方法调用
Person.print()  //静态方法调用  使用静态属性、静态方法前要加类名

Guess you like

Origin blog.csdn.net/m0_63779088/article/details/126489180