NodeJs中类定义及类使用

2,328 阅读1分钟

转:www.cnblogs.com/eczhou/p/78…

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