JS 中的静态方法

原生JS(es5)中的静态方法:

//原生JS中的静态方法

function Person(name, age) {
    this.name = name;
    this.age = age;
    this.run = function () {
        console.log(`${this.name} is ${this.age}岁`)
    }
}

Person.prototype.sex = '男'
Person.prototype.work = function () {
    console.log(`${this.name} is ${this.sex} and ${this.age}岁`)
}

//静态方法
Person.fun = function () {
    console.log("fun 静态方法")
}

var p = new Person('jack', 20) //实例方法是通过实例化来调用的
p.run()
p.work()
Person.fun() //静态方法调用,直接通过类名调用

/**
 * jack is 20岁
   jack is 男 and 20岁
   fun 静态方法
 */

ES6 中的静态方法:

通过 static 关键字

//es6里面的静态方法
class Person {
    constructor(name) {
        this._name = name;  //属性
    }
    run() {  //实例方法
        console.log("实例方法",this._name);
    }
    static work() {   //静态方法
        console.log('work 静态方法');
    }
}

Person.value = '这是一个静态方法的属性';

var p = new Person('jack');
p.run();
Person.work();   //es6里面的静态方法执行

console.log(Person.value);

/**
 * 实例方法 jack
   work 静态方法
   这是一个静态方法的属性
 */

  

原文地址:https://www.cnblogs.com/shanlu0000/p/13172474.html