一、call
function a() {
// 此时this指向函数b,相当于把函数b拿过来作为自己,所以可以调用函数b的方法属性内容
b.call(this)
}
function b(){
this.username = 'test call'
}
// 定义:调用一个对象的一个方法,以另一个对象替换当前对象。
/**
* thisObj的取值有以下4种情况:
(1) 不传,或者传null,undefined, 函数中的this指向window对象
(2) 传递另一个函数的函数名,函数中的this指向这个函数的引用
(3) 传递字符串、数值或布尔类型等基础类型,函数中的this指向其对应的包装对象,如 String、Number、Boolean
(4) 传递一个对象,函数中的this指向这个对象
*/
let c = new a()
console.log(c.username)
function class1() {
this.name = function () {
console.log('class1内的方法!')
}
}
function classs2() {
class1.call(this) //此行代码执行后,当前的this指向了class1(也可以说class2继承了class1)
}
let f = new classs2()
f.name()
function eat(x,y){
console.log(x+y);
}
function drink(x,y){
console.log(x-y);
}
eat.call(drink,3,2);
function Animal(){
this.name = 'shark'
this.showName=function(){
console.log(this.name);
}
}
function Dog(){
this.name="dog";
// Animal.call(this); // 取消注释,会将this 传递给animal中
}
var animal=new Animal();
var dog=new Dog();
animal.showName.call(dog);
二、apply
/**
* 二、apply()
语法:apply([thisObj[,argArray]])
定义:应用某一对象的一个方法,用另一个对象替换当前对象。
说明:
如果 argArray 不是一个有效的数组或者不是 arguments 对象,那么将导致一个 TypeError。
如果没有提供 argArray 和 thisObj 任何一个参数,那么 Global 对象将被用作 thisObj, 并且无法被传递任何参数。
call 和 apply的区别
对于 apply、call 二者而言,作用完全一样,只是接受参数的方式不太一样。
*/
function class1(...arg) {
this.name = function () {
console.log(arg)
}
}
function class2() {
let args1 = 1;
let args2 = 2;
//class1.call(this,args1,args2)
class1.apply(this,[args1,args2])
}
let Class2 = new class2();
Class2.name()
/**
* call 需要把参数按顺序传递进去,而 apply 则是把参数放在数组里。
既然两者功能一样,那该用哪个呢?
在JavaScript 中,某个函数的参数数量是不固定的,因此要说适用条件的话,当你的参数是明确知道数量时用 call ;
而不确定的时候用 apply,然后把参数 push 进数组传递进去。当参数数量不确定时,函数内部也可以通过 arguments 这个数组来遍历所有的参数。
*/
三、bind
/**
*bind是在EcmaScript5中扩展的方法(IE6,7,8不支持)
bind() 方法与 apply 和 call 很相似,也是可以改变函数体内 this 的指向。
MDN的解释是:bind()方法会创建一个新函数,称为绑定函数,当调用这个绑定函数时,绑定函数会以创建它时传入 bind()方法的第一个参数作为 this,
传入 bind() 方法的第二个 以及以后的参数加上绑定函数运行时本身的参数 按照顺序 作为原函数的参数来调用原函数。
#注意:bind方法的返回值是函数#
*/
let bar = function () {
console.log(this.x)
}
let foo = {
x:1
}
bar.bind(foo)()
// 或
let func = bar.bind(foo);
func()
function log(){
var args = Array.prototype.slice.call(arguments);
args.unshift('(app)');
console.log.apply(console, args);
};
log(1,2)