NodeJs中类定义及类使用

本文介绍如何在JavaScript中定义一个简单的类Point,并演示如何创建类实例及调用类方法,包括静态方法和静态变量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值