js中call()的用法详解

227 阅读1分钟

js中call()的用法详解

all和apply可以用来重新定义函数的执行环境,也就是this的指向; call 和 apply 都是为了改变某个函数运行时的 context 即上下文而存在的 换句话说,就是为了改变函数体内部 this 的指向。因为 JavaScript 的函数存在「定义时上下文」和「运行时上下文」以及「上下文是可以改变的」这样的概念。

func1.call(func2,argument1,argument2) 如上,call的作用就是把func1的方法放到func2上使用,后面的argument1..这些做为参数传入。

function add (x, y) 
{ 
    console.log (x + y);
} 
function sub (x, y) 
{ 
    console.log (x - y); 
} 
add.call (sub , 1, 1);    //2 

这个例子中的意思就是用 add 来替换 sub ,add.call(sub ,1,1) 等价于 add(1,1) ,所以运行结果为:console.log (2); // 注意:js 中的函数其实是对象,函数名是对 Function 对象的引用。

A.call( B,x,y ):就是把A的函数放到B中运行,x 和 y 是A方法的参数。

用call来实现继承,用this可以继承myfunc1中的所有方法和属性。

function myfunc1(){
    this.name = '张三';
    this.say = function(name) {
        console.log('我是',name);
    }
}
 
function myfunc2(){
    myfunc1.call(this);
}
 
var myfunc3 = new myfunc2();
myfunc3.say('李四'); // 我是 李四
console.log (myfunc3.name);	// 张三