手写系列– call,apply

0次阅读

共计 1149 个字符,预计需要花费 3 分钟才能阅读完成。

作用

call 和 apply 用来调用函数,并用指定对象(第一个参数)替换函数的 this 值,同时用指定数组替换函数的参数
我自己不用声明一个构造函数,就借用现成的构造函数,从而精简代码

代码
<!DOCTYPE html>
<html lang=”en”>

<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<meta http-equiv=”X-UA-Compatible” content=”ie=edge”>
<title>Document</title>
</head>

<body>
<script>
var obj = {
value: ‘1’
}

function fn(name, age) {
this.name = name;
this.age = age;
this.say = function() {
alert(this.name + this.age)
}
}
</script>
<!– call –>
<script>
Function.prototype.call2 = function(context) {
var context = context || window;
context.fn = this;
var args = [];
for (var i = 1; i < arguments.length; i++) {
args.push(‘arguments[‘ + i + ‘]’);
}
var result = eval(‘context.fn(‘ + args + ‘)’);
delete context.fn
return result;
}
fn.call(obj, ‘jie’, 10)
obj.say()
fn.call2(obj, ‘biao’, 20)
obj.say()
</script>
<!– apply –>
<script>
Function.prototype.apply2 = function(context, arr) {
var context = Object(context) || window;
context.fn = this;

var result;
if (!arr) {
result = context.fn();
} else {
var args = [];
for (var i = 0, len = arr.length; i < len; i++) {
args.push(‘arr[‘ + i + ‘]’);
}
result = eval(‘context.fn(‘ + args + ‘)’)
}
delete context.fn
return result;
}
fn.apply(obj, [‘jie’, 10])
obj.say()
fn.apply2(obj, [‘biao’, 20])
obj.say()
</script>
</body>

</html>
效果

正文完
 0