js中的call及apply的运用

格式:

obj.call(thisObj, arg1, arg2, ...);  参数为字符 obj.apply(thisObj, [arg1, arg2, ...]); 参数为数组

例一:sub函数赋值给this 

其实就是动态的改变this了,下面例子就说明了。。。
function add(a, b){
    console.dir(this);
}
function sub(a, b){
    console.dir(this);
} 
add(1,2);                         "Window" 
sub(1,2);                         "Window" 
add.call(sub, 1, 2);          "sub(a, b)" 
sub.apply(add, [1, 2]);    "add(a, b)"
--------------------------------------------
function add(j, k){
    alert(j+k);
    this(j,k);
}

function sub(j, k){
    alert(j-k);
}
add.call(sub, 5, 3); //把sub函数赋值给this 输出8  2
add.apply(sub, [5, 3]); //8  2        

例二: 点击把#content赋值给函数中的this来改变颜色和样式

function color() {
    this.style.color = 'red';
}
function size() {
    this.style.fontSize = '54px';
}
window.onload = function() {
    document.getElementById('content').onclick = function() {
        color.call(this);
        size.apply(this);
    }
}

hello  点击后变成  hello

例三:通过call和apply,我们可以实现child对象继承parent。

var Parent = function(){
    this.name = "yjc";
    this.age = 22;
}
var child = {};
console.log(child);//Object {} ,空对象
Parent.call(child);
console.log(child); //Object {name: "yjc", age: 22}
原文地址:https://www.cnblogs.com/xujian2016/p/6084990.html