显性混入
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!");},});
如果直接调用 Vehicle.drive() ,函数调用中的 this 会绑定到 Vehicle 对象而不是 Car 对象。(如果 Car.drive() 的名称标识符和 Vehicle.drive() 没有重叠则不需要使用 .call(this) 进行绑定。)
