ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 5일차 공부내용
    JavaScript 2021. 7. 21. 02:25

    1. Class

    1.1 Prototype

    When you refer to methods that are available on instances of a class, you are referring to prototype methods. 

    JavaScript performs dynamic dispatch using the prototype chain.

    Using a number sign (#) has emerged as a popular convention for describing prototype methods. 

    Car.prototype.shift can be written simply as Car#shift.(only text, not code)

    Every function has a special property called prototype.

    The object instance stores this in its __proto__ property.

    1.1.1 Dynamic Dispatch(dispatch)

    When you attempt to access a property or method on an object, if it doesn’t exist, JavaScript checks the object’s prototype to see if it exists there. Because all instances of a given class share the same prototype.

    Java‐Script will walk up the prototype chain until it finds a prototype that satisfies the request.

    If it can find no such prototype, it will finally error out. 

    If you need instances to have initial data values, it’s better to set them in the constructor.

    const car1 = new car;
    console.log(car.prototype.shift);
    console.log(car1.shift === car.prototype.shift);
    console.log(car1.prototype.shift);
    console.log(car1.__proto__)

    result

    ƒ shift(gear) { this.usergear = gear; }
    
    true
    
    Uncaught TypeError: Cannot read property 'shift' of undefined
    
    {constructor: ƒ, shift: ƒ}
    constructor: class car
    shift: ƒ shift(gear)
    usergear: (...)
    get usergear: ƒ usergear()
    set usergear: ƒ usergear(value)
    __proto__: Object
    const car2 = new car;
    console.log(car1.shift === car2.shift);
    console.log(car2.__proto__)

    result

    true
    
    {constructor: ƒ, shift: ƒ}
    constructor: class car
    shift: ƒ shift(gear)
    usergear: (...)
    get usergear: ƒ usergear()
    set usergear: ƒ usergear(value)
    __proto__: Object

    1.2 Static Methods

    So far, the methods we’ve considered are instance methods.

    In a static method, this is bound to the class itself, but it’s generally considered best practice to use the name of the class instead of this.

    Static methods are used to perform generic tasks that are related to the class, but not any specific instance. 

    class Car {
        static getNextVin() {
            return Car.nextVin++; 	// we could also use this.nextVin++
    				// but referring to Car emphasizes
    				// that this is a static method
        }
        constructor(make, model) {
            this.make = make;
            this.model = model;
            this.vin = Car.getNextVin();
        }
        static areSimilar(car1, car2) {
            return car1.make===car2.make && car1.model===car2.model;
        }
        static areSame(car1, car2) {
            return car1.vin===car2.vin;
        }
    }
    Car.nextVin = 0;
    
    const car1 = new Car("Tesla", "S");
    const car2 = new Car("Mazda", "3");
    const car3 = new Car("Mazda", "3");
    
    car1.vin; // 0
    car2.vin; // 1
    car3.vin  // 2
    
    Car.areSimilar(car1, car2); // false
    Car.areSimilar(car2, car3); // true
    Car.areSame(car2, car3); // false
    Car.areSame(car2, car2); // true

    1.3 Inheritance

    class Vehicle {
        constructor() {
            this.passengers = [];
            console.log("Vehicle created");
        }
        addPassenger(p) {
            this.passengers.push(p);
        }
    }
    
    class Car extends Vehicle {
        constructor() {
            super();
            console.log("Car created");
        }
        deployAirbags() {
            console.log("BWOOSH!");
        }
    }

    Inheritance works only one way. Instances of the Car class can access all methods of the Vehicle class, but not the other way around. 

    const v = new Vehicle();
    v.addPassenger("Frank");
    v.addPassenger("Judy");
    v.passengers; // ["Frank", "Judy"]
    const c = new Car();
    c.addPassenger("Alice");
    c.addPassenger("Cameron");
    c.passengers; // ["Alice", "Cameron"]
    v.deployAirbags(); // error
    c.deployAirbags(); // "BWOOSH!"

    1.4 Polymorphism

    The intimidating word polymorphism is OO parlance for treating an instance as a member of not only its own class, but also any superclasses. 

    In JavaScript, which is not typed, any object can be used anywhere (though that doesn’t guarantee correct
    results), so in a way, JavaScript has the ultimate polymorphism.

    Very often in JavaScript, the code you write employs some form of duck typing. This technique comes from the expression “if it walks like a duck, and quacks like a duck…it’s probably a duck.”

    JavaScript does provide the instanceof operator, which will tell you if an object is an instance of a given class. 

    class Motorcycle extends Vehicle {}
    const c = new Car();
    const m = new Motorcyle();
    c instanceof Car; // true
    c instanceof Vehicle; // true
    m instanceof Car; // false
    m instanceof Motorcycle; // true
    m instanceof Vehicle; // true

    1.5 Enumerating Object Properties

    If you use ES6 classes as they’re intended to be used, data properties will always be defined on instances, not in the prototype chain. However, because there’s nothing to prevent adding properties directly to the prototype, it’s always best to use hasOwnProperty to be sure.

    class Super {
        constructor() {
            this.name = 'Super';
            this.isSuper = true;
        }
    }
    
    // this is valid, but not a good idea...
    Super.prototype.sneaky = 'not recommended!';
    
    class Sub extends Super {
        constructor() {
            super();
            this.name = 'Sub';
            this.isSub = true;
        }
    }
    
    const obj = new Sub();
    
    for(let p in obj) {
        console.log(`${p}: ${obj[p]}` +
        (obj.hasOwnProperty(p) ? '' : ' (inherited)'));
    }

    Result

    name: Sub
    isSuper: true
    isSub: true
    sneaky: not recommended! (inherited)

    The properties name, isSuper, and isSub are all defined on the instance, not in the prototype chain (note that properties declared in the superclass constructor are defined on the subclass instance as well). The property sneaky, on the other hand, was manually added to the superclass’s prototype.
    You can avoid this issue altogether by using Object.keys, which includes only properties defined on the prototype.

    1.6 String Representation

    Every object ultimately inherits from Object, so the methods available on Object are by default available for all objects. One of those methods is toString, whose purpose is to provide a default string representation of an object.

    class Car {
        toString() {
            return `${this.make} ${this.model}: ${this.vin}`;
    }

     

    'JavaScript' 카테고리의 다른 글

    5일차 공부내용 3  (0) 2021.07.21
    5일차 공부내용 2  (0) 2021.07.21
    4일차 공부내용 2  (0) 2021.07.20
    4일차 공부내용  (0) 2021.07.20
    3일차 공부 내용  (0) 2021.07.19
Designed by Tistory.