JavaScript(call/apply)

147 阅读1分钟

call 和 apply的作用:

  • 改变this指向


call 和 apply的区别:

  • 后面传的参数形式不同
  • call 需要把实参按照形参的个数传递进去
  • apply 需要传一个arguments


例:

function Color (c, sitColor) {  
  this.c = c;  
  this.sitColor = sitColor;
}
function Model (height, width, len) {  
  this.height = height;  
  this.width = width;  
  this.len = len;
}
function Car (c, sitColor, height, width, len) {  
  Color.call(this, c, sitColor);  
  Model.call(this, height, width, len);

  Color.apply(this, [c, sitColor]);
  Model.apply(this, [height, width, len]);
}
var myCar = new Car(100, 'red', 150, 200, 600);


题:JavaScript中call和apply的作用是什么,区别是什么?

  • 作用是改变this指向,区别是参数不同