一句话介绍call:
call()方法在使用一个指定的this值和若干个指定的参数值的前提下调用某个函数或方法。
请看以下这个代码:
var foo = {
value: 1
};
function bar() {
console.log(this.value);
}
bar.call(foo); // 1
这就是关于call函数的使用:改变了this的指向,指向到foo。
那我们来模拟实现一下这里的call函数的功能(改变this指向):
第一步,我们试想 如果在foo函数中存在这样一个bar对象,这样我的bar对象就可以调用foo函数里的value,此时的this也正好指向foo,也就是这样:
var foo = {
value: 1,
bar: function() {
console.log(this.value)
}
};
foo.bar(); // 1
这里就可以看到,我们的this确实是指向了foo,但是问题来了,这时我们的foo函数多了一个bar属性,这不合理,所以我们要加delete将它删除掉。
所以我们实现call函数的步骤就将是:
- 将函数设为对象的属性
- 执行该函数
- 删除该函数
思路就像这样:
foo.fn = bar
foo.fn();
delete foo.fn;
于是以这样的思路我们可以试着写一下call函数的实现:
Funciton.protetype.call1 = function(context){
context.fn = this;
context.fn();
delete context.fn;
}
var foo = {
value:1;
};
function bar() {
console.log(this.value);
}
bar.call1(foo); //1
很神奇,实现了call函数的功能,成功打印出1。
还有个要注意的地方:
this参数可以传null,当为null的时候,视为指向window
所以改版我们的代码:
Funciton.protetype.call1 = function(context){
var context = context || window;
context.fn = this;
context.fn();
delete context.fn;
}
var value = 1;
function bar() {
console.log(this.value);
}
bar.call1(null); //1
很棒吶,一个call函数就这样实现了~~
网友评论