Javascrip中call和apply的用途

本文详细介绍了JavaScript中this关键字的指向问题及其解决方法,包括使用call和自定义bind函数来改变函数调用上下文。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


  • 改变this的指向 var obj1 = { name:'seven' } var obj2 = { name:'name' } window.name = 'window'; var getName = function(){ console.log(this.name); };

    getName() // output window
    getName.call(obj1) // output seven
    getName.call(obj2) // output name
    复制代码
  • Function.prototype.bind Function.prototype.bind = function(context){ var self = this; // save the origin function context return function(){ // return new function return self.apply(context,arguments); // use context replace the new function this } }

    var obj = {
      name:'name'
    }
    
    var func = function(){
      console.log(this.name);
    }.bind(obj);
    
    func(); // name
    复制代码

    优化版本的bind Function.prototype.bind = function(){ var _this = this, context = [].shift.call(arguments), // 获取传入的运行环境 args = [].slice.call(arguments); // 获取第一次传入的参数

    	return function(){
    		return _this.apply(context,[].concat.call(args,[].slice.call(arguments)));
    	}
    }
    
    var obj = {
    	name:'name'
    }
    
    var func = function(a,b,c,d){
    	console.log(this.name);
    	console.log([a,b,c,d]);
    }.bind(obj,12,23);
    
    func(34,45);
    复制代码
  • 借用其他对象的方法 Array.prototype.slice.call(arguments)比如这个最常见的转换arguments为数组的hack写法就是一种借用Array的slice方法来转换arguments。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值