javascript中的 bind、apply和call的理解

这三个函数在实际使用中 可能会产生意想不到的好效果

基本理解:

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


参考资料
-https://juejin.im/post/5c52703e6fb9a049a42f7735

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值