[觀念] 物件實體與變數觀念,require,export

image

{name:'Peter', age:26} 是「物件實體」
a是「變數名稱」,指定到「物件實體」
b同樣也是「變數名稱」,跟a一樣,指定到同一個「物件實體」
a跟b是兩個變數,但是指向到同一個「物件實體」
所以當使用b變數去改變物件實體的內容時,用a去查閱同一個物件實體,得到改變後的內容

class Person {
    constructor(name = 'noname', age = 20) {//建構涵式
        this.name = name;//this在這裡是instance,實體的意思,.name是屬性,從「類別」輸入的變數會被視為「區域變數」,放到this實體的name屬性中
        this.age = age;
    }
    toJSON() {// toJSON是一個定義在類別Person裡面的一個方法
        const obj = {
            name: this.name,
            age: this.age,
        };
        return JSON.stringify(obj);
    }
}
module.exports = Person; // node 匯出類別

同樣在這邊的 module.exports = Person 是匯出Person的參照,不是重做一個類別,而是把參照匯出。

const Person = require('./person'); 就是把參照匯入成Person

參照的原文就是reference


module.exports = Person; 是匯出一個參照

也可以匯出成陣列或物件,(參考:https://forum.stdb.org/t/topic/30679)

匯出成陣列:module.exports = [Person,Person2];
匯出成物件:module.exports = {Person,Person2};