JavaScript 中 call()、apply()、bind() 的用法


JavaScript 中 call()、apply()、 bind()的用法

var name="cristiano.Zhao"
var info = {
     name:"cris",
     objAge: this.age,
     myFunc: function(){
            console.log(this.name + "年龄" + this.age);
     }
}

打印结果

info.objAge;  //27
obj.myFunc()  // cris name undefind

分析:在 console 打印中,this 指向 info, 因此,name打印出 cris,  而 age 打印 undefind.

call()、apply()、bind() 都是用来重定义 this 这个对象的!

var name="Georgina ",age=27;
var other={
     name:"cristiano.Zhao",
     objAge:this.age,
     myFunc:function(){
         console.log(this.name + "年龄" + this.age);
    }
}

var example = {
    name:"cris",
    age:"27"
}


obj.myFunc.call(example);   // cris  27
obj.myFunc.apply(example);  // cris  27
obj.myFunc.bind(example)();  // cris  27

 三个函数参数结构中,第一个参数都是指向 this 对象

        1、对 call 来讲,参数直接传递,例如 obj.myFunc(example, "male", "front-end");

        2、对 apply 来讲,所有参数都必须放在一个数组里面传进去, 例如 obj.myFunc.apply(example, ["male", "front-end"]);

        3、对 bind 来讲,参数传递与 call 相同,但是返回一个函数,因此要立即执行之后,才能正确执行;