apply、call和bind方法
他们的作用一模一样,都是为了改变函数体内部this的指向,只是传参形式的不同。
call(thisObj, arg1, arg2, arg3, arg4);
apply(thisObj, [args]);
bind(thisObj,arg1, arg2, arg3, arg4);
thisObj:call和apply第一个参数是一样的,该参数将替代Function类里面的this对象。
arg1,arg2…:是一个个的参数,
args:一个数组或类数组,是一个参数列表。
call:
var obj = {
name: 'linxin'
}
function func(firstName, lastName) {
console.log(firstName + ' ' + this.name + ' ' + lastName);
}
func.call(obj, 'C', 'D'); // C linxin D
apply:
var obj = {
name : 'linxin'
}
function func(firstName, lastName){
console.log(firstName + ' ' + this.name + ' ' + lastName);
}
func.apply(obj, ['A', 'B']); // A linxin B
bind
var obj = {
name: 'linxin'
}
function func(firstName, lastName) {
console.log(firstName + ' ' + this.name + ' ' + lastName);
}
var name = func.bind(obj,'C', 'D');
name(); // C linxin D
apply、call和bind的用法
改变函数作用域
var name = "小白";
var obj = {
name:"小红";
};
function sayName(){
return this.name;
}
console.log(sayName.call(this)); //小白
console.log(sayName.call(obj)); //小红
借用别的对象的方法
var Person1 = function () {
this.name = 'linxin';
}
var Person2 = function () {
this.getname = function () {
console.log(this.name);
}
Person1.call(this);
}
var person = new Person2();
person.getname(); // linxin
从上面我们看到,Person2 实例化出来的对象 person 通过 getname 方法拿到了 Person1 中的 name。因为在 Person2 中,Person1.call(this) 的作用就是使用 Person1 对象代替 this 对象,那么 Person2 就有了 Person1 中的所有属性和方法了,相当于 Person2 继承了 Person1 的属性和方法。
实现继承
function Person(name,height){
this.sayInfo = function(){
return "姓名:" + name + ", 身高:" + height + ", 体重:" + this.weight;
}
}
function Chinese(name, height, weight) {
Person.call(this, name, height);
this.weight = weight;
this.nation = function() {
console.log("我是中国人");
}
}
//子类
function America(name, height, weight) {
Person.apply(this, [name, height]);
this.weight = weight;
}
let chiness = new Chinese("成龙", "178cm", "60kg");
console.log(chiness.sayInfo()); //姓名:成龙, 身高:178cm, 体重:60kg
let america = new America("jack", "180cm", "55kg");
console.log(america.sayInfo()); //姓名:jack, 身高:180cm, 体重:55kg