这三个函数在实际使用中 可能会产生意想不到的好效果
基本理解:
func.bind(context, arg1, arg2, …)
这样使用返回一个新函数,新函数内的上下文 “this”,会被bind()中的第一个参数代替,新函数的函数参数,会被bind()函数的第二个参数及后续参数 一一替换
- 第一步:
var func = function() {
console.log(this);
};
func(); // 在浏览器环境下 会输出 <window.object>, 使用了严格模式"use strict"会输出 undefined
- 第二步:
var func = function() {
console.log(this);
}.bind(1);
func(); // 输出 1
- 第三步:
var func = function() {
console.log(this);
}.bind(this);
func(); // 在浏览器环境下 会输出 <window.object>, 使用了严格模式"use strict"仍然会输出 <window.object>
上面代码中,变量 func 被赋值为 function() { console.log(this);}.bind(this);
注意 bind()是返回一个新的Function,所以func的类型还是Function,只是内部的this被bind(this)中的第一个参数this替换了;
- 第四步:
// 在浏览器环境下
var a = 1;
var b = 2;
var func = function(a, b) {
console.log(this);
console.log(a);
console.log(b);
}
func(a, b); # 输出 <window.object>, 1,2 严格模式下 undefined,1,2
var a = 1;
var b = 2;
var func = function(a, b) {
console.log(this);
console.log(a);
console.log(b);
}.bind(this,3 ,4);
func(a, b); # 输出 <window.object>, 3,4 严格模式下 undefined,3,4
func.call(context,arg1,arg2,…)
这个函数 与bind()不同的是,它并不会返回一个新函数,而是直接在func上修改 func的上下文“this”和对应的函数参数 并执行;
var a = 1;
var b = 2;
var func = function(a, b) {
console.log(this);
console.log(a);
console.log(b);
};
func(a, b);
func(a, b); // 输出 <window.object>, 1, 2 严格模式下 undefined, 1, 2
---
var a = 1;
var b = 2;
var func = function(a, b) {
console.log(this);
console.log(a);
console.log(b);
};
func.call(this, 3, 4); // 输出 <window.object>, 3, 4 严格模式下 <window.object>, 3, 4
func.apply(context,args)
这个函数 与call()一样,直接修改func函数对象,唯一不同的是它只有两个参数,第二个参数是一个 函数参数 数组。将会依次替换func函数对象的参数
var a = 1;
var b = 2;
var func = function(a, b) {
console.log(this);
console.log(a);
console.log(b);
};
func(a, b);
func(a, b); // 输出 <window.object>, 1, 2 严格模式下 undefined, 1, 2
---
var a = 1;
var b = 2;
var func = function(a, b) {
console.log(this);
console.log(a);
console.log(b);
};
func.apply(this, [3, 4]); // 输出 <window.object>, 3, 4 严格模式下 <window.object>, 3, 4
实际应用:
回调匿名函数
$.ajax({
type : "POST",
contentType: "application/json;charset=UTF-8",
url : "http://url",
data : JSON.stringify(data),
success : function(result) {
console.log(this); // 该处的this不会是全局对象(严格模式下为 undefined),该处的this与 $.ajax() 作用域 所处的上下文this一致
}.bind(this)
});
回调函数执行时处理
var obj = {
foo: 'bar',
func: function(cb) {
cb.call(this);
}
};
// 回调函数
var callback = function() {
console.log(this.foo);
};
obj.func(callback); // 输出bar callback内的this 被指向了obj