模拟apply和call
<html> <head> <script type="text/javascript"> Function.prototype.Apply = function (obj, arr) { obj = obj || window; obj._tempFunction = this; var rv; if (!arr) { rv = obj._tempFunction(); } else { var args = []; for (var i = 0, len = arr.length; i < len; i++) { args.push('arr[' + i + ']'); } rv = eval("obj._tempFunction(" + args + ")"); } delete obj._temFunction; return rv; } Function.prototype.Call = function () { return this.Apply(Array.prototype.shift.Apply(arguments), arguments); } var obj = {}; function f(a,b,c) { console.log(this == obj);//看看Apply和Call 是不是把函数内的this 指向了 obj对象 console.log(a + b + c); } f(1, 2, 3); f.Apply(obj, [4, 5, 6]); f.Call(obj, 7, 8, 9); </script> </head> <body> </body> </html>
相关推荐
chunianyo 2020-06-04
xjp 2020-05-26
owilson 2020-05-07
Alanxz 2020-03-04
wangyayun0 2020-02-11
歆萌 2020-02-10
chunianyo 2019-12-18
chunianyo 2019-12-12
APCDE 2019-12-10
herionliu 2017-09-02
herionliu 2018-06-01
ififg 2018-06-01
zheglei 2017-09-02
herionliu 2016-03-23
herionliu 2015-07-08
zheglei 2015-04-23