显性混入

  1. function mixin(sourceObj, targetObj) {
  2. for (var key in sourceObj) {
  3. if (!(key in targetObj)) {
  4. targetObj[key] = sourceObj[key];
  5. }
  6. }
  7. return targetObj;
  8. }
  9. var Vehicle = {
  10. engines: 1,
  11. ignition: function () {
  12. console.log("Turning on my engine.");
  13. },
  14. drive: function () {
  15. this.ignition();
  16. console.log("Steering and moving forward");
  17. },
  18. };
  19. var Car = mixin(Vehicle, {
  20. wheels: 4,
  21. drive: function () {
  22. Vehicle.drive.call(this);
  23. console.log("Rolling on all " + this.wheels + " wheels!");
  24. },
  25. });

如果直接调用 Vehicle.drive() ,函数调用中的 this 会绑定到 Vehicle 对象而不是 Car 对象。(如果 Car.drive() 的名称标识符和 Vehicle.drive() 没有重叠则不需要使用 .call(this) 进行绑定。)