ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 4일차 공부내용 2
    JavaScript 2021. 7. 20. 22:32

    1. Class

    class Car {
    	constructor(make, model) {
    		this.make = make;
    		this.model = model;
    		this.userGears = ['P', 'N', 'R', 'D'];
    		this.userGear = this.userGears[0];
    	}
    	shift(gear) {
    		if(this.userGears.indexOf(gear) < 0)
    		throw new Error(`Invalid gear: ${gear}`);
    		this.userGear = gear;
    	}
    }
    const car1 = new Car("Tesla", "Model S");
    const car2 = new Car("Mazda", "3i");
    car1.shift('D');
    car2.shift('R');

    1.1 Dynamic  Properties

    This protection is limited because there’s nothing to stop you from setting it directly: car1.userGear = 'X'.

    Java‐Script has no such mechanism to protect against this kind of abuse by allowing you to specify the access level of methods and properties.

    Dynamic properties can help mitigate this weakness.

    class Car {
    	constructor(make, model) {
    		this.make = make;
    		this.model = model;
    		this._userGears = ['P', 'N', 'R', 'D'];
    		this._userGear = this._userGears[0];
    	}
    	get userGear() { return this._userGear; }
    	set userGear(value) {
    	if(this._userGears.indexOf(value) < 0)
    		throw new Error(`Invalid gear: ${value}`);
    		this._userGear = vaule;
    	}
    	shift(gear) { this.userGear = gear; }
    }

    We haven’t eliminated the problem as we can still set _userGear directly: car1._userGear = 'X'. 

    prefixing properties we consider private with an underscore. This is protection by convention only, allowing you to quickly spot code that’s accessing properties that it shouldn’t be.

     

    If you really need to enforce privacy, you can use an instance of WeakMap 10) that’s protected by scope (if we don’t use WeakMap, our private properties will never go out of scope, even if the instances they refer to do).

    const Car = (function() {
    	const carProps = new WeakMap();
    	class Car {
    		constructor(make, model) {
    			this.make = make;
    			this.model = model;
    			this._userGears = ['P', 'N', 'R', 'D'];
    			carProps.set(this, { userGear: this._userGears[0] });
    		}
    	get userGear() { return carProps.get(this).userGear; }
    	set userGear(value) {
    		if(this._userGears.indexOf(value) < 0)
    			throw new Error(`Invalid gear: ${value}`);
    		carProps.get(this).userGear = value;
    	}
    	shift(gear) { this.userGear = gear; }
    	}
    	return Car;
    })();

    1.2 A class is really just a function.

    class Es6Car {} // we'll omit the constructor for brevity
    function Es5Car {}
    > typeof Es6Car // "function"
    > typeof Es5Car // "function"

     

    'JavaScript' 카테고리의 다른 글

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