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