簡體   English   中英

帶有 require 的 Node.js ES6 類

[英]Node.js ES6 classes with require

所以到目前為止,我已經通過以下方式在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;

現在使用 ES6,您可以像這樣創建“實際”類:

class Animal{

 constructor(name){
    this.name = name ;
 }

 print(){
    console.log('Name is :'+ this.name);
 }
}

現在,首先,我喜歡這個 :) 但它提出了一個問題。 你如何結合node.js的模塊結構來使用它?

假設您有一個類,為了演示,您希望在其中使用模塊 假設您希望使用fs

所以你創建你的文件:


動物.js

var fs = require('fs');
class Animal{

 constructor(name){
    this.name = name ;
 }

 print(){
    console.log('Name is :'+ this.name);
 }
}

這是正確的方法嗎?

另外,您如何將此類公開給我的節點項目中的其他文件? 如果你在一個單獨的文件中使用它,你仍然能夠擴展這個類嗎?

我希望你們中的一些人能夠回答這些問題:)

是的,您的示例可以正常工作。

至於公開你的類,你可以像其他任何東西一樣export一個類:

class Animal {...}
module.exports = Animal;

或者更短的:

module.exports = class Animal {

};

一旦導入到另一個模塊中,您就可以將其視為在該文件中定義的:

var Animal = require('./Animal');

class Cat extends Animal {
    ...
}

只需將 ES6 類名稱與您在 ES5 方式中處理構造函數名稱相同即可。 他們是一樣的。

ES6 語法只是語法糖,它創建了完全相同的底層原型、構造函數和對象。

因此,在您的 ES6 示例中:

// animal.js
class Animal {
    ...
}

var a = new Animal();

module.exports = {Animal: Animal};

您可以將Animal視為對象的構造函數(就像您在 ES5 中所做的那樣)。 您可以導出構造函數。 您可以使用new Animal()調用構造函數。 使用它的一切都是一樣的。 只有聲明語法不同。 甚至還有一個Animal.prototype有你所有的方法。 ES6 方式確實創建了相同的編碼結果,只是使用了更好/更好的語法。


在進口方面,這將像這樣使用:

const Animal = require('./animal.js').Animal;

let a = new Animal();

此方案將 Animal 構造函數導出為.Animal屬性,這允許您從該模塊導出不止一件東西。

如果您不需要導出不止一件事,您可以這樣做:

// animal.js
class Animal {
    ...
}

module.exports = Animal;

然后,使用以下命令導入它:

const Animal = require('./animal.js');

let a = new Animal();

ES6 的 require 方式是import 您可以使用import { ClassName } from 'path/to/ClassName'語法export您的類並將其導入其他地方。

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';

在節點中使用類 -

這里我們需要 ReadWrite 模塊並調用 makeObject(),它返回 ReadWrite 類的對象。 我們用來調用方法。 索引.js

const ReadWrite = require('./ReadWrite').makeObject();
const express = require('express');
const app = express();

class Start {
  constructor() {
    const server = app.listen(8081),
     host = server.address().address,
     port = server.address().port
    console.log("Example app listening at http://%s:%s", host, port);
    console.log('Running');

  }

  async route(req, res, next) {
    const result = await ReadWrite.readWrite();
    res.send(result);
  }
}

const obj1 = new Start();
app.get('/', obj1.route);
module.exports = Start;

讀寫.js

這里我們創建了一個 makeObject 方法,它確保只有在對象不可用時才返回對象。

class ReadWrite {
    constructor() {
        console.log('Read Write'); 
        this.x;   
    }
    static makeObject() {        
        if (!this.x) {
            this.x = new ReadWrite();
        }
        return this.x;
    }
    read(){
    return "read"
    }

    write(){
        return "write"
    }


    async readWrite() {
        try {
            const obj = ReadWrite.makeObject();
            const result = await Promise.all([ obj.read(), obj.write()])
            console.log(result);
            check();
            return result
        }
        catch(err) {
            console.log(err);

        }
    }
}
module.exports = ReadWrite;

有關更多解釋,請訪問https://medium.com/@nynptel/node-js-boiler-plate-code-using-singleton-classes-5b479e513f74

在類文件中,您可以使用:

module.exports = class ClassNameHere {
 print() {
  console.log('In print function');
 }
}

或者您可以使用此語法

class ClassNameHere{
 print(){
  console.log('In print function');
 }
}

module.exports = ClassNameHere;

另一方面,要在任何其他文件中使用此類,您需要執行這些步驟。 首先使用以下語法要求該文件: const anyVariableNameHere = require('filePathHere');

然后創建一個對象const classObject = new anyVariableNameHere();

在此之后,您可以使用classObject訪問實際的類變量

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM