js中的apply和call方法

2017-09-18  本文已影响10人  流星大石头
js中call和apply的用法
    通俗的讲,apply和call就是为了改变函数体内部this的指向.

    1.call()方法
    用法:
        <1> obj.call(thisObj,arg1,arg2,...)
        把obj(this)绑定到thisObj,这个时候thisObj具备了obj的属性和方法,或者说thisObj继承了obj的属性和方法.

    2.apply()方法:
        用法:
        <1>obj.apply(thisObj,[arg1,arg2,...])
         把obj(this)绑定到thisObj,这个时候thisObj具备了obj的属性和方法,或者说thisObj继承了obj的属性和方法.

    区别:apply接受的是数组参数,call接受的是连续参数.
//1.实现继承:
    var Parent = function () {
        this.name = "mayun";
        this.age = 18;
    }
    var child = {};
    console.log(child) //打印结果: {}
    Parent.call(child)
    console.log(child)//打印结果: {name:"mayun",age:18}

    //2.劫持别人的方法:
    var test1 = {
        name:"test1",
        showName: function () {
            console.log(this.name)
        }
    }

    var test2 = {
        name:"test2"
    };
    test1.showName.call(test2) //打印结果:test2
    //此时showName中的this指针指向了test2,this.name就是test2.name
上一篇 下一篇

猜你喜欢

热点阅读