call bind apply 改变函数中的this
// 函数是一个对象
var fn = new Function();
function fn() {};
// 证明fn是Function的实例(对象)
console.log(fn.__proto__ === Function.prototype); //true
console.dir(fn);
function fn(x, y) {
console.log(this);
console.log(x + y);
}
fn(5, 6); // this->window
call()
- 调用函数,改变函数中的this
- 第一个参数 设置函数内部this的指向
- 函数的返回值 call的返回值就是函数的返回值
function fn(x, y) {
console.log(this);
console.log(x + y);
}
var obj = {
name: 'zs'
}
fn.call(obj, 5, 6); // this-> {"name": "zs"}. 11
apply()
- 调用函数,改变函数中的this
- 第一个参数 设置函数内部this的指向
- 第二个参数 是数组
- 函数的返回值 call 的返回值就是函数的返回
function fn(x, y) {
console.log(this);
console.log(x + y);
}
var obj = {
name: 'zs'
}
fn.apply(obj, [5, 6]); // this-> {"name": "zs"}. 11
bind()
- 改变函数中的this,不会调用函数,而是把函数复制一份
- 第一个参数 设置函数内部this的指向
- 其它参数,对应函数的参数
- 函数的返回值 call的返回值就是函数的返回值
function fn(x, y) {
console.log(this);
console.log(x + y);
}
var obj = {
name: 'zs'
}
fn.bind(obj, 5, 6);
// this-> function fn(x, y) {console.log(this);console.log(x + y);}
f();