-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfunction.call2.html
More file actions
62 lines (52 loc) · 1.39 KB
/
function.call2.html
File metadata and controls
62 lines (52 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
Function.prototype.call2 = function(context) {
var context = context || window; //因为传进来的context有可能是null
context.fn = this;
var args = [];
for (var i = 1; i < arguments.length; i++) {
args.push("arguments[" + i + "]"); //不这么做的话 字符串的引号会被自动去掉 变成了变量 导致报错
}
console.log(args)
args = args.join(",");
var result = eval("context.fn(" + args + ")"); //相当于执行了context.fn(arguments[1], arguments[2]);
delete context.fn;
return result; //因为有可能this函数会有返回值return
}
Function.prototype.call3 = function(context) {
let args = [],
ctx = context || window;
ctx.fn = this;
for (var i = 0, l = arguments.length; i < l; i++) {
args.push("arguments["+ i +"]");
}
args = args.join(",");
var res = eval("ctx.fn("+ args +")");
delete ctx.fn;
return res;
}
Function.prototype.call3 = function(obj) {
return this.apply(obj, arguments);
}
function Foo(obj) {
this.name = obj.name;
}
Foo.prototype.getName = function() {
return this.name
}
var foo = new Foo({
name: 'foo'
});
var name = foo.getName.call2({
name: 'foo2'
});
console.log(name)
</script>
</body>
</html>