NodeJs中類定義及類使用


1、首先定義類Point,文件名為point.class.js:

// 定義類
class Point {
    //構造函數
    constructor(x, y) {
        this.x = x;//類中變量
        this.y = y;
    }
    //類中函數
    toString() {
        return '(' + this.x + ', ' + this.y + ')';
    }
    //靜態函數
    static sayHello(name){
        //修改靜態變量
        this.para = name;
        return 'Hello, ' + name;
    }
}
//靜態變量
Point.para = 'Allen';
module.exports = Point;

2、創建文件test.js,在該文件中創建類對象並使用

//引入類,暫時ES6標准中有import,但NodeJs還不支持
var Point = require('./Point.class');
//新建類對象
var point = new Point(2, 3);
//調用對象中的方法
console.log(point.toString());
//調用類中的靜態函數
console.log(Point.sayHello('Ence'));
//調用類中的靜態變量
console.log(Point.para);

運行test.js,輸出:

(2, 3)
Hello, Ence
Ence

 


免責聲明!

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



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