Classes: proto chain, private fields + assert (*)

devfish·2023년 1월 16일
0

Javascript

목록 보기
22/30

auto-created constructor and prototype chain

Just by 1) using extends to establish inheritance, 2) having a constructor function in the upmost class, the prototype chain is established. This is because the constructor function is auto-created in the children classes when it's omitted.

*Don't confuse __proto__ & .prototype!

instance private field vs. instance properties

const assert = require('assert');

class Person {
    #firstName; // (A)
    constructor(firstName) {
      this.#firstName = firstName; // (B)
    }

    describe() {
        return `Person named ${this.#firstName}`;
      }

    static extractNames(persons) {
    return persons.map(person => person.#firstName);
    }

}

let sung = new Person('Sung');
let jeyoun = new Person ('Jeyoun');
// console.log(sung.describe());
// console.log(Person.extractNames([sung, jeyoun]));
// console.log(sung.#firstName); //error 

const tarzan = new Person('Tarzan');

assert.strictEqual(tarzan.describe(),'Person named Tarzan');
assert.strictEqual(1, '1'); 

//배열/오브제 값비교
assert.deepEqual(
    Person.extractNames([tarzan, new Person('Cheeta')]),
    ['Tarzan', 'Cheetah']
  );
// console.log(assert);
  • #firstName is an instance private field: Such fields are stored in instances. They are accessed similarly to properties, but their names are separate – they always start with hash symbols (#). And they are invisible to the world outside the class

UpMostClass.__proto__: Object.prototype!

assert()

  • Handy object methods to compare values, for 'testing'
  • only stops and throws an error when the two values expected to be the same are actually different

References

Node.js: assert

Classes(ES6) - JS for impatient programmers

profile
la, di, lah

0개의 댓글