有关于call和apply的使用

125 阅读1分钟
function test(){
  console.log('a');
}
test(); // 这个是我们看到的代码

但是其实,系统在test ( );上是加上了一个隐式的方法的,如下:

function test(){
  console.log('a');
}
test.call();

有关于call和apply方法的具体操作示例:

function Car(brand,color){
  this.brand = brand;
  this.color = color;
}

	var newCar = { };
	Car.call(newCar, 'Benz','Red');
	console.log( newCar );

首先我们要知道,newCar一开始只是一个空的对象,但是当我们使用call方法的时候,我们在括号里传入了newCar,然后还赋上了实参,这个时候再打印,就会是调用的call前面的构造函数,结果就是brand:benz color:red.

也就是说,Car里面的this指向,被call方法改变了,从一开始的指向Car,变成了现在指向newCar.

apply的具体示例:

function Car(brand,color){
  this.brand = brand;
  this.color = color;
}

	var newCar = { };
	Car.apply(newCar, ['Benz','Red']);
//只有一个区别,就是apply使用的是数组.两种写法一模一样的效果.
//apply会使用的多一点.
	console.log( newCar );

同时,我们是可以new对象去打印到car原有的属性的:

function Car(brand,color){
  this.brand = brand;
  this.color = color;
  this.run = function(){
    console.log('running');//方法也是可以apply到的.
  }
}

	var newCar = { 
  	displacement = '3.0'; 
// 在打印newCar的时候一样可以打印出来,自己对象里有的属性,就在自己的属性里去打印,没有的就去apply的构造函数里拿.
  };
	Car.call(newCar, 'Benz','Red');
	console.log( newCar );

var car = new Car('Benz','Red');
	console.log(car);

一个计算器的案例

function Compute(){
  this.plus = function(a,b){
    console.log(a+b);
  }
  this.minus = function(a,b){
    console.log(a-b);
  }
  function FullCompute(){
    
    Compute.apply(this);
    
    this.mul = function(a,b){
      console.log(a*b);
    }
    this.div= function(a,b){
    console.log(a/b);
  } 
}
  var compute = new FullCompute();
  compute.plus(1,2);
  compute.minus(1,2);
  compute.mul(1,2);
  compute.div(1,2);