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