前端面试总结-call,apply的区别

202 阅读1分钟

每个函数都包含两个非继承而来的方法:call()方法和apply()方法。 call 和 apply 都是为了解决改变 this 的指向。作用都是相同的,只是传参的方式不同。 两者作用一致,都是把obj(即this)绑定到thisObj,这时候thisObj具备了obj的属性和方法。或者说thisObj『继承』了obj的属性和方法。绑定后会立即执行函数。

除了第一个参数外,call 可以接收一个参数列表,apply 只接受一个参数数组。

let a = {
    value: 1
}
function getValue(name, age) {
    console.log(name)
    console.log(age)
    console.log(this.value)
}
getValue.call(a, 'yck', '24')
getValue.apply(a, ['yck', '24'])

调用函数,传递参数

  //定义一个add 方法
    function add(x, y) {
        return x + y;
    }

    //用call 来调用 add 方法
    function myAddCall(x, y) {
        //调用 add 方法 的 call 方法
        return add.call(this, x, y);
    }

    //apply 来调用 add 方法
    function myAddApply(x, y) {
        //调用 add 方法 的 applly 方法
        return add.apply(this, [x, y]);
    }

    console.log(myAddCall(10, 20));    //输出结果30
  
    console.log(myAddApply(20, 20));  //输出结果40

改变函数作用域

var name = '小白';

    var obj = {name:'小红'};

    function sayName() {
        return this.name;
    }

    console.log(sayName.call(this));    //输出小白

    console.log(sayName. call(obj));    //输入小红

高级用法,实现 js 继承

 //父类 Person
    function Person() {
        this.sayName = function() {
            return this.name;
        }
    }

    //子类 Chinese
    function Chinese(name) {
        //借助 call 实现继承
        Person.call(this);
        this.name = name;

        this.ch = function() {
            alert('我是中国人');
        }
    }

    //子类 America
    function America(name) {
        //借助 call 实现继承
        Person.call(this);
        this.name = name;

        this.am = function() {
            alert('我是美国人');
        }
    }


    //测试
    var chinese = new Chinese('成龙');
    //调用 父类方法
    console.log(chinese.sayName());   //输出 成龙

    var america = new America('America');
    //调用 父类方法
    console.log(america.sayName());   //输出 America
function add(c,d){
        return this.a + this.b + c + d;
    }

    var s = {a:1, b:2};
    console.log(add.call(s,3,4)); // 1+2+3+4 = 10
    console.log(add.apply(s,[5,6])); // 1+2+5+6 = 14

原生js封装call

Function.prototype.myCall = function (context, ...arg) {
        // const fn = Symbol('临时属性')
        // context[fn] = this
        // console.log(context,'context')
        // context[fn](...arg)
        // delete context[fn]
        // console.log(this(1))
        this.bind(context,...arg)()
    }

    function ma (A){
       console.log(A)
       console.log(this)
    }
    var ma1={
        s:99
    }
ma.myCall(ma1,222)