【JavaScript】js中的call方法

moziila官方文档链接https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/call
fun.call(thisArg[, arg1[, arg2[, ...]]])
1.其中fun表示原始的方法对象;
2.参数:
  thisArg表示最终使用的对象;
  arg1和arg2为该方法的参数。
简单的说,就是使用:原始方法对象.call(最终的对象,方法参数列表),这样就使得原始方法中的用到的this对象变成了最终的对象,而不是原始方法所对应的对象。
//如下实例:
function B(){
    this.name = 'kitty';
    this.age = 24;
    this.say = function(){
        console.debug(this.name)
    };
}

function C(){
    this.name = 'tab';
}
var c = new C();
console.debug(b.say.call(c));//就是将b对象中的say方法的调用者对象this替换为c对象,那么此时say方法中的this对象就是c对象了。
---------------------------------------
上面代码的console打印结果:

---------------------------------------

3.【注】:使用call方法可以实现继承:
   可以让call()中的对象调用当前对象所拥有的function。你可以使用call()来实现继承:写一个方法,然后让另外一个新的对象来继承它(而不是在新对象中再写一次这个方法)。
function Old(age){
    this.age = age;
    this.type = age>18?'adult':'children';
};

function Sub(){
    this.name = 'son';
    this.subM = function(age){
        Old.call(this,age);
    }
}
var s  = new Sub();
console.debug('未调用父类构造方法前的type属性是:'+s.type)
console.debug('未调用父类构造方法前的子类对象是:')
console.debug(s)
console.debug('------------------------------------------------');
s.subM(111)
console.debug('已调用父类构造方法前的type属性是:'+s.type)
console.debug('已调用父类构造方法后的子类对象是:')
console.debug(s)

//通过在子类的构造函数中调用父类的构造函数,实现了将原先定义在父类构造函数中的属相创建及赋值操作在此时由于使用了call方法将this指向了子类对象,因此此时该父类构造方法将属性添到了子类对象上。

--------------------------------------------------------------

上面代码的console打印结果:

--------------------------------------------------------------

 
 
原文地址:https://www.cnblogs.com/tabchanj/p/5919250.html