《你不知道的JavaScript-上卷》第二部分-this和对象原型-笔记-4-混合对象“类”

45 阅读1分钟

4.4 混入

在继承或者实例化时,JavaScript 的对象机制并不会自动执行复制行为。由于在其他语言中类表现出来的都是复制行为,因此 JavaScript 开发者也想出了一个方法来模拟类的复制行为,这个方法就是混入。

4.4.1 显式混入

手动实现复制功能

function mixin(sourceObj, targetObj) {
    for (var key in sourceObj) {
        if (!(key in targetObj)) {
            targetObj[key] = sourceObj[key];
        }
    }
    return targetObj;
}
var Vehicle = {
    engines: 1,
    ignition: function () {
        console.log("Turning on my engine.");
    },
    drive: function () {
        this.ignition();
        console.log("Steering and moving forward!");
    }
};
var Car = mixin(Vehicle, {
    wheels: 4,
    drive: function () {
        Vehicle.drive.call(this);
        console.log(
            "Rolling on all " + this.wheels + " wheels!"
        );
    }
});
Car.drive();
//Turning on my engine.
//Steering and moving forward!
//Rolling on all 4 wheels!

4.4.2 隐式混入

利用了 this 的重新绑定功能,把的赋值操作都会应用在 Another 对象上而不是Something 对象上

 var Something = {
            cool: function () {
                this.greeting = "Hello World";
                this.count = this.count ? this.count + 1 : 1;
            }
        };
        Something.cool();
        Something.greeting; // "Hello World"
        Something.count; // 1

        var Another = {
            cool: function () {
                // 隐式把 Something 混入 Another
                Something.cool.call(this);
            }
        };
        Another.cool();
        Another.greeting; // "Hello World"
        Another.count; // 1(count 不是共享状态)