call 、 apply 、bind 都是 js function 函数当中自带的方法,用来改变当前函数 this 的指向。
call() 方法
语法格式:
function.call(thisArg, arg1, arg2, ...)
该方法可以传递一个 thisArgs 参数和一个参数列表;
thisArgs 指定了函数在运行期的调用者,也就是函数中的 this 对象,而参数列表会被传入调用函数中。
** thisArgs 的取值有以下4种情况:**
- 不传,或者传 null , undefined , 函数中的 this 指向 window 对象
- 传递另一个函数的函数名,函数中的this指向这个函数的引用
- 传递字符串、数值或布尔类型等基础类型,函数中的this指向其对应的包装对象,String、Number、Boolean
- 传递一个对象,函数中的this指向这个对象
function a(){
console.log(this); //输出函数a中的this对象
}
function b(){} //定义函数b
var obj = {name:'onepixel'}; //定义对象obj
a.call(); //window
a.call(null); //window
a.call(undefined); //window
a.call(1); //Number
a.call(''); //String
a.call(true); //Boolean
a.call(b); // function b(){}
a.call(obj); //Object
复制代码
** 下面是 call 的核心用法:它允许在一个对象上调用该对象没有定义的方法,并且这个方法可以访问其它对象中的属性 **
let a = {
name:'onepixel', //定义a的属性
say:function(){ //定义a的方法
console.log("Hi,I'm function a!");
}
};
function b(name){
console.log("Post params: "+ name);
console.log("I'm "+ this.name);
this.say();
}
b.call(a,'test')
// Post params: test
// I'm onepixel
// Hi,I'm function a!
复制代码
apply() 方法
语法格式:
function.apply(thisArg[, argsArray])
apply 和 call 的唯一区别是第二个参数的传递方式不同:
apply 的第二个参数必须是一个数组,而 call 允许传递一个参数列表。
bind() 方法
语法格式:
function.bind(thisArg[, arg1[, arg2[, ...]]])
bind()
的作用与call()
和apply()
一样,都是可以改变函数运行时上下文,它传参与call()
类似;它们三者的区别是call()
和apply()
在调用函数之后会立即执行,而bind()
方法调用并改变函数运行时上下文后,返回一个新的函数,供需要时再调用。
对比 call、 apply、 bind 如下:
let person = {
name: '提莫',
age: 10
}
let obj = {
name:'盖伦',
age: 11,
myFunc: function(from, to){
console.log(this.name + ',年龄:' + this.age + ',来自' + from + ',去往' + to)
}
}
obj.myFunc.call(person,'班德尔','德玛西亚') // 提莫,年龄:10,来自班德尔,去往德玛西亚
obj.myFunc.apply(person,['班德尔','德玛西亚']) // 提莫,年龄:10,来自班德尔,去往德玛西亚
obj.myFunc.bind(person,'班德尔','德玛西亚')() // 提莫,年龄:10,来自班德尔,去往德玛西亚
obj.myFunc.bind(person,['班德尔','德玛西亚'])() // 提莫,年龄:10,来自班德尔,德玛西亚,去往undefined
复制代码
本文参考摘录了
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END