call()和apply()方法(切换上下文)

call方法:
语法:call([thisObj[,arg1[, arg2[, [,.argN]]]]])
定义:调用一个对象的一个方法,以另一个对象替换当前对象。


apply方法:
语法:apply([thisObj[,argArray]])
定义:应用某一对象的一个方法,用另一个对象替换当前对象。


适用于继承和多重继承

单继承
function Animal(name){
  this.name = name;
  this.showName = function(){
    alert(this.name);
  }
}

function Cat(name){
  Animal.call(this, name);
}

var cat = new Cat("Black Cat");
cat.showName();

多继承
function Class10()
{
  this.showSub = function(a,b)
  {
  alert(a-b);
  }
}

function Class11()
{
  this.showAdd = function(a,b)
  {
  alert(a+b);
  }
}

function Class2()
{
  Class10.call(this);
  Class11.call(this);
}

原文地址:https://www.cnblogs.com/GerryOfZhong/p/5219651.html