Using “Object.create” instead of “new”

后端 未结 15 2181
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 06:08

Javascript 1.9.3 / ECMAScript 5 introduces Object.create, which Douglas Crockford amongst others has been advocating for a long time. How do I replace new

15条回答
  •  鱼传尺愫
    2020-11-22 06:53

    I prefer a closure approach.

    I still use new. I don't use Object.create. I don't use this.

    I still use new as I like the declarative nature of it.

    Consider this for simple inheritance.

    window.Quad = (function() {
    
        function Quad() {
    
            const wheels = 4;
            const drivingWheels = 2;
    
            let motorSize = 0;
    
            function setMotorSize(_) {
                motorSize = _;
            }
    
            function getMotorSize() {
                return motorSize;
            }
    
            function getWheelCount() {
                return wheels;
            }
    
            function getDrivingWheelCount() {
                return drivingWheels;
            }
            return Object.freeze({
                getWheelCount,
                getDrivingWheelCount,
                getMotorSize,
                setMotorSize
            });
        }
    
        return Object.freeze(Quad);
    })();
    
    window.Car4wd = (function() {
    
        function Car4wd() {
            const quad = new Quad();
    
            const spareWheels = 1;
            const extraDrivingWheels = 2;
    
            function getSpareWheelCount() {
                return spareWheels;
            }
    
            function getDrivingWheelCount() {
                return quad.getDrivingWheelCount() + extraDrivingWheels;
            }
    
            return Object.freeze(Object.assign({}, quad, {
                getSpareWheelCount,
                getDrivingWheelCount
            }));
        }
    
        return Object.freeze(Car4wd);
    })();
    
    let myQuad = new Quad();
    let myCar = new Car4wd();
    console.log(myQuad.getWheelCount()); // 4
    console.log(myQuad.getDrivingWheelCount()); // 2
    console.log(myCar.getWheelCount()); // 4
    console.log(myCar.getDrivingWheelCount()); // 4 - The overridden method is called
    console.log(myCar.getSpareWheelCount()); // 1
    

    Feedback encouraged.

提交回复
热议问题