多重继承 -Javascript中的apply与call详解

举例

//定义一个函数 function add(x, y) { return x + y; } //用call 来调用 function myAddCall(x, y) { //调用 add 方法 的 call 方法 return add.call(this, x, y); } //apply 来调用 function myAddApply(x, y) { //调用 add 方法 的 applly 方法 return add.apply(this, [x, y]); } console.log(myAddCall(10, 20)); //输出结果30 console.log(myAddApply(20, 20)); //输出结果40

 eg2: 

function isArray1(obj) {
  return Object.prototype.toString.call(obj) === '[object Array]';
}
let o1 = {
  a: '1'
};
console.log(isArray1(o1))
console.log(o1.toString() === '[object Array]')

 add: bind

var obj = {
  a: 1,
  b: 2,
  getCount: function(c, d) {
    return this.a + this.b + c + d;
  }
};
 
Function.prototype.bind = Function.prototype.bind || function(context) {
  var that = this;
  return function() {
    // console.log(arguments); // console [3,4] if ie<6-8>
    return that.apply(context, arguments);
 
  }
}
window.a = window.b = 0;
var func = obj.getCount.bind(obj);
console.log(func(3, 4));  // 10

 

eg3:

        var x = 0;
        function test(option) {
            if(option){
            console.log(option );
            console.log(option.x);
            console.log(this)
            }
        }

        var o = {};
        o.x = 1;
        o.m = test;
        o.m.apply(); //0
        o.m.apply(o,[{x:2}]); //1

  
apply与call 实际是改变被执行函数的上下文;
补充:

a.call(b);

a.apply(b,[])

apply与call 实现函数的继承

 本质是实现 a 对象到b对象的继承 ,既 b继承a / b包含了a 的所有参数和函数 并传参数给a  参数形式不同,在对象b的作用域下 执行了函数a,

转载于:https://www.cnblogs.com/tongbiao/p/6845662.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值