所以到現在爲止,我已經創建類和模塊在node.js
方式如下:Node.js的ES6班,需要
var fs = require('fs');
var animalModule = (function() {
/**
* Constructor initialize object
* @constructor
*/
var Animal = function (name) {
this.name = name;
};
Animal.prototype.print = function() {
console.log('Name is :'+ this.name);
};
return {
Animal: Animal
}
}());
module.exports = animalModule;
與ES6
現在,您可以使「真正的」類就像這樣:
class Animal{
constructor(name){
this.name = name ;
}
print(){
console.log('Name is :'+ this.name);
}
}
現在,首先,我喜歡這個:)但它引發了一個問題。你如何結合使用node.js
的模塊結構?
假設你有一個類,你希望使用一個模塊用於演示的目的說你想使用fs
所以創建文件:
Animal.js
var fs = require('fs');
class Animal{
constructor(name){
this.name = name ;
}
print(){
console.log('Name is :'+ this.name);
}
}
這是正確的方法嗎?
此外,如何將此類暴露給我的節點項目中的其他文件?如果你在一個單獨的文件中使用它,你仍然可以擴展這個類嗎?
我希望你們中的一些將能夠回答這些問題:)
只要將ES6類的名稱與您以ES5方式處理構造函數名相同即可。他們是一樣的。 ES6語法只是語法糖,並創建完全相同的底層原型,構造函數和對象。 – jfriend00
無論如何,創建「animalModule」的IIFE在具有自己的模塊範圍的節點模塊中是毫無意義的。 – Bergi