在看《你不知道的JavaScript》中,有一段关于继承的mixin实现,代码如下:function mixin( sourceObj, targetObj ) {//sourceObj中不在targetObj中的key,添加到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!只是调用了drive()方法,为什么ignition()中的内容也被打印了那?是哪里使用的不对吗?
添加回答
举报
0/150
提交
取消