通过简单的command(命令)模式,理解apply, call, 作用域
(function(){ var carManager = { requestInfo:function(model,id){ return 'the infomation for '+model+' with ' + id+' is in foobar'; }, buyVehicle:function(model,id){ return 'you hava successed buy '+model+' with ' + id+' '; }, arrangeViewing:function(){} }; carManager.execute = function(name){ return carManager[name] && carManager[name].apply(carManager,[].slice.call(arguments,1)); }; carManager.execute('requestInfo','mini','1234'); })();
carManager[name] && carManager[name].apply(carManager,[].slice.call(arguments,1));
先从[].slice.call(arguments,1);开始说起,[]空数组使用slice方法,call(作用域,参数)。等于arguments.slice(1);并将结果返回到[]空数组里面。最后结果得到数组['mini','1234']
接着是carManager[name].apply(carManager,['mini','1234']);apply(作用域,参数(数组));将carManager[name]的作用域设置为(对象carManager),再把参数穿进去