NODEJS(10)Book Read - hands-on-nodejs.pdf - pseudo class

本文介绍了Node.js中如何创建和使用自定义模块,并通过一个Line伪类实例展示了如何实现对象继承及模块封装。此外,还说明了如何利用npm进行模块打包及发布。

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

NODEJS(10)Book Read - hands-on-nodejs.pdf - pseudo class

3. Making Modules
A pseudo-class
var Line = function(x1, y1, x2, y2) {
     this.x1 = x1;
     this.y1 = y1;
     this.x2 = x2;
     this.y2 = y2;   
};

Line.prototype.length = function() {
     return Math.sqrt(
          Math.pow(Math.abs(this.x1 - this.x2),2) +
          Math.pow(Math.abs(this.y1 - this.y2),2)
     );
};

module.exports.create = function(x1, y1, x2, y2) {
     return new Line(x1, y1, x2, y2);
};

That is a pseudo-class which named Line, when we use it we can do like this,
var Line = require(‘./line’);
var line = Line.create(2,4,10,15);
console.log(‘this line length is ‘ + line.length());

A psedo-class that inherits
var util = require(‘util’);
var EventEmitter = require(‘events’).EventEmitter;

var Line = function(x1, y1, x2, y2) {
     …snip...
};

util.inherits(Line, EventEmitter);

Line.prototype.length = function() {
     …snip...
};

node_modules and NPM bundle

I can commit my modules to git, and then, who plan to use it can do like this.

For example, this is for the tool AES, package.json
{
     "name"               :     "sillycat-aes",
     "version"          :     "0.1.0",
     "description"     :     "Module for AES encryption and descritpion",
     "main"               :      "lib/app.js"
}

When we plan to use it, we do like this, package.json
{
     "name"               :     "sillycat-platform",
     "version"          :     "0.1.0",
     "description"     :     "Sillycat Platform, provide all kinds of tools.",
     "main"               :      "lib/app.js",
     "dependencies"     :     {
          "sillycat-aes"     :     "git://github.com/luohuazju/sillycat-aes.git"
     }
}

Just use NPM command to install that.
>npm install


References:
package.json
http://docs.spmjs.org/doc/package
http://blog.uifanr.com/2013/03/13/478
http://blog.youkuaiyun.com/zimin1985/article/details/18958741


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值