Mar*_*sen 83 javascript node.js ecmascript-6
到目前为止,我已经node.js通过以下方式创建了类和模块:
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;
Run Code Online (Sandbox Code Playgroud)
现在使用ES6,您可以像这样制作"实际"类:
class Animal{
constructor(name){
this.name = name ;
}
print(){
console.log('Name is :'+ this.name);
}
}
Run Code Online (Sandbox Code Playgroud)
现在,首先,我喜欢这个:)但它提出了一个问题.你如何结合node.js模块结构使用它?
假设您有一个课程,您希望使用模块,以便演示说您想使用 fs
所以你创建你的文件:
Animal.js
var fs = require('fs');
class Animal{
constructor(name){
this.name = name ;
}
print(){
console.log('Name is :'+ this.name);
}
}
Run Code Online (Sandbox Code Playgroud)
这是正确的方法吗?
另外,如何将此类公开给我的节点项目中的其他文件?如果你在一个单独的文件中使用它,你还能扩展这个类吗?
我希望你们中的一些人能够回答这些问题:)
ros*_*dia 125
是的,你的例子可以正常工作.
至于暴露你的课程,你可以export像其他任何课程一样:
class Animal {...}
module.exports = Animal;
Run Code Online (Sandbox Code Playgroud)
或者更短:
module.exports = class Animal {
};
Run Code Online (Sandbox Code Playgroud)
导入到另一个模块后,您可以将其视为在该文件中定义:
var Animal = require('./Animal');
class Cat extends Animal {
...
}
Run Code Online (Sandbox Code Playgroud)
只需处理ES6类名称就像处理ES5方式中的构造函数名称一样.他们是一样的.
ES6语法只是语法糖,并创建完全相同的底层原型,构造函数和对象.
所以,在您的ES6示例中:
// animal.js
class Animal {
...
}
var a = new Animal();
module.exports = {Animal: Animal};
Run Code Online (Sandbox Code Playgroud)
你可以Animal像对象的构造函数一样对待(就像在ES5中一样).您可以导出构造函数.你可以调用构造函数new Animal().使用它的一切都是一样的.只有声明语法不同.甚至还有一个Animal.prototype拥有你所有方法的东西.ES6方式确实创建了相同的编码结果,只需使用更高级/更好的语法.
在导入方面,这将使用如下:
const Animal = require('./animal.js').Animal;
let a = new Animal();
Run Code Online (Sandbox Code Playgroud)
此方案将Animal构造函数.Animal导出为允许您从该模块导出多个内容的属性.
如果您不需要导出多个东西,可以这样做:
// animal.js
class Animal {
...
}
module.exports = Animal;
Run Code Online (Sandbox Code Playgroud)
然后,导入它:
const Animal = require('./animal.js');
let a = new Animal();
Run Code Online (Sandbox Code Playgroud)
ES6 的 require 方式是import. 您可以export使用import { ClassName } from 'path/to/ClassName'语法将类导入到其他地方。
import fs from 'fs';
export default class Animal {
constructor(name){
this.name = name ;
}
print(){
console.log('Name is :'+ this.name);
}
}
import Animal from 'path/to/Animal.js';
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
98551 次 |
| 最近记录: |