JavaScript中的call和apply的用法?

call的用法:

1.修改this指向

obj = {
  name:'liumcb'
}
function func() {
    console.log(this); 
}
func();     ------- 指向window
func.call(obj);   --------指向obj

2.借用别的对象的方法:

  var Person1 = function () {
    this.name = 'linxin';
  }
  var Person2 = function () {
    this.getname = function () {
      console.log(this.name);
    }
    console.log('this===', this);  ------ 指向 Person2 {getname: ƒ}
    Person1.call(this);  ------ 作用:使用 Person1 对象代替 this 对象
  }
  var person = new Person2();
  console.log('person===', person);   ---- Person2 {name: "linxin", getname: ƒ}
  person.getname();

在Person1.call(this): 使用 Person1 对象代替 this 对象, 那么 Person2 就有了 Person1 中的所有属性和方法了,相当于 Person2 继承了 Person1 的属性和方法。

3.调用函数

function func() {
    console.log('linxin');
}
func.call();            // linxin

apply、call 方法都会使函数立即执行,因此它们也可以用来调用函数。

 

------------恢复内容开始------------

call的用法:

1.修改this指向

obj = {
  name:'liumcb'
}
function func() {
    console.log(this); 
}
func();     ------- 指向window
func.call(obj);   --------指向obj

2.借用别的对象的方法:

  var Person1 = function () {
    this.name = 'linxin';
  }
  var Person2 = function () {
    this.getname = function () {
      console.log(this.name);
    }
    console.log('this===', this);  ------ 指向 Person2 {getname: ƒ}
    Person1.call(this);  ------ 作用:使用 Person1 对象代替 this 对象
  }
  var person = new Person2();
  console.log('person===', person);   ---- Person2 {name: "linxin", getname: ƒ}
  person.getname();

在Person1.call(this): 使用 Person1 对象代替 this 对象, 那么 Person2 就有了 Person1 中的所有属性和方法了,相当于 Person2 继承了 Person1 的属性和方法。

3.调用函数

function func() {
    console.log('linxin');
}
func.call();            // linxin

apply、call 方法都会使函数立即执行,因此它们也可以用来调用函数。

简而意之:就是 A.call(B),call()可以让括号里的对象来继承括号外函数的属性。

 

------------恢复内容结束------------

原文地址:https://www.cnblogs.com/liumcb/p/13680188.html