call、apply/bind的区别和用法(简单粗暴的解释)
var obj1={ name:"bob", age:20 } var obj2={ name:"coco", age:22 } function getAge(){ console.log(this.age) } var age = 50; getAge(); //50 等价window.getAge(); getAge.call(obj1) //20 //相当于callback getAge.apply(obj2)//22 //让函数服务于不同的对象; call和apply的区别 var str = { name:"wow", age:"18", search:function(sex,addr){ console.log(this.name+ "和性别" + sex + "和地址" + addr ) } } var str1 = { name:20 } var str2 = { name:23 } str.search.call(str1,"男","江西") //20和性别男和地址江西 str.search.apply(str2,["女","湖北"]) //23和性别女和地址湖北 总结:区别就是apply传参是数组; call继承函数对象的属性: function Person(){ this.name = "bow", this.like = "吃东西" } function Son(){ Person.call(this); //等价于Person(); this.stre = "你好" } var aa = new Person(); console.log(aa); var bb = new Son(); console.log(bb)
bind使用 var name = "name -g" var obj = { name:"bob" getName:function(){ console.log(this.name); //动态绑定,运行时,是谁做的。 } } obj.getName();//输出bob var fn = obj.getName; fn(); //等价于window.fn();输出"name -g"; var fn1 = obj.getName.bind(obj); fn1();//输出bob;