1、Array.prototype.slice.apply(arguments,[0/1/2])函数,截取调用函数传来的参数,[0],所有,[1],返回 222,33,55。 [2]返回,33,55
<script type="text/javascript"> function test(){ //将参数转为一个数组 var args = Array.prototype.slice.apply(arguments,[1]); //alert(args); } test(11,222,33,55); </script>
2、Function.apply(obj,args)函数, obj:这个对象将代替Function类里this对象, args:这个是数组,它将作为参数传给Function(args-->arguments)
<script type="text/javascript">
- var parent = {
- method: function () {
- console.log(this);
- }
- };
var arr = {}; arr.name = function(name){ console.log('name:'+name); }; function info(fun){ var args = Array.prototype.slice.apply(arguments,[1]); fun.apply(this,args); } info(arr['name'],'stelin'); </script>
3、这段js值得收藏
<script type="text/javascript"> var _func = {}; function inits(){ console.log('inits'); } function a(){ console.log('aa'); } function addFunctionItem(item,fun){ if(!_func[item]){ _func[item] = []; } _func[item] = $.merge(_func[item],[fun]);//[fun]作为数组对象合并 } function operateFuncs(item){ if(!_func[item]){ _func[item] = []; } args = Array.prototype.slice.apply(arguments, [1]); //参数截取 返回[1,2] '[1]'表示截取1后面的所有参数(0开始) alert(args); $.each(_func[item],function(){ this.apply(this,args);//循环数组中函数,传参数,执行函数,函数必须保持在数组中,才能这样用 }); } var _theme = function(fun) { var args = Array.prototype.slice.apply(arguments, [1]); return (_theme[fun] || _theme.prototype[fun]).apply(this, args); } _theme.prototype = {}; _theme.prototype.loginLink = function (username){ return 'your name'+username; } _theme.prototype.logout = function (username){ return 'logout your'+username; } addFunctionItem('func',inits()); //这样初始化,默认数组_func里面为空[函数执行] console.log('1:'+_func['func']); addFunctionItem('func',a()); console.log('2:'+_func['func']); //默认执行函数 addFunctionItem('func',function after(name,age){console.log('after_log-'+name+'_'+age)});////这样初始化,默认数组_func里面不为空[函数不执行] addFunctionItem('func',function out(name,age){console.log('out_log-'+name+'_'+age)}); console.log('after:'+_func['func']); var args = {}; operateFuncs('func',1,2); //这样在来执行没有执行的函数 _theme.prototype.loginLink = function (username){ return 'your name tow '+username; //覆盖之前 } _theme.prototype.logout = function (username){ return 'logout your two '+username; } var name = _theme('loginLink','stelin'); console.log(name); console.log(_theme('logout','stelin')); </script>