call
作用
方法重用
使用 call() 方法,您可以编写能够在不同对象上使用的方法。
示例1
function A() {
this.a = 1;
this.a1 = 1;
this.aFun = function(){
}
}
function B() {
A.call(this);
this.b = 2;
this.b1 = 2;
}
console.log(new A());//{a: 1, a1: 1, aFun: ƒ}
console.log(new B());//{a: 1, a1: 1, b: 2, b1: 2, aFun: ƒ}
上面的示例 是 将A中的属性与方法 通过 A.call(this)这句话给放到了B中,注意 prototype 中的属性与方法 是不是放到B中的,这种方法只能继承普通的元素与方法
示例2
var person = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
var person1 = {
firstName:"Bill",
lastName: "Gates",
}
var person2 = {
firstName:"Steve",
lastName: "Jobs",
}
console.log('1.1',person.fullName.call(person1)); //1.1 Bill Gates
console.log('1.2',person.fullName.call(person2)); //1.2 Steve Jobs
上述示例将person.fullName 的作用域进行更改,1.1 中fullName.call(person1) 是将fullName 中的this 指向 person1 ,这样 this.firstName 其实就是 person1.firstName 。所以最后输出的结果是Bill Gates
1.2 的结果为1.2 Steve Jobs
apply
此方法作用与 call 方法一样 都是 Function.prototype 中的一个方法,
实现的作用也是完全一样的。不同点是传递的参数不一样,call 方法是,传递多个参数。apply 是传递一个数组
示例
var b = function(t1,t2,t3){
console.log(this.name,t1,t2,t3);
}
var c = function(){
this.name = "c";
}
console.log(b.call(c,1,2,3))//c 1 2 3
console.log(b.apply(c,[1,2,3]))//c 1 2 3
bind
bind 与 call、apply 一样 也是 Function.prototype 中的一个方法,区别在于 bind 这个方法 会返回一个 绑定了作用域的一个方法,不会立即执行,而call,apply 在调用中就立即执行了
示例
var b = function(t1,t2,t3){
console.log(this.name,t1,t2,t3);
}
var c = function(){
this.name = "c";
}
var fun = b.bind(c);//不绑定传入参数
var fun1 = b.bind(c,1,2,3);//可以绑定传入参数
console.log(fun())//c undefined undefined undefined
console.log(fun(1,2,3))//c 1 2 3
console.log(fun1())//c 1 2 3
总结
1.call、apply、bind 都可以实现改变函数作用域的作用
2.call、apply 调用后立即执行,bind 是返回一个函数
3.call 、bind 是传入多个参数 apply 是传入一个数组
本人菜鸟一枚,如果发现有什么不对的地方,欢迎大家的指正~