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 靜態方法
   這是一個靜態方法的屬性
 */

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM