JS的函数方法:call() apply() bind() 自定义绑定对象

把方法绑定到对应的对象上,那么该对象就不用再重写一遍相同的方法了,这样就达到了重复利用的目的。

一、bind方法

使用bind重新绑定对象。

function foo() {
    console.log('绑定对象为:',this);
}
foo();
var f1 = foo.bind({x:1});
f1();
var f2 = foo.bind(document);
f2();

二、apply方法

自行设置绑定对象,传入数组作为参数。

function foo(x, y) {
    console.log('结果' ,x+y);
    console.log('绑定对象', this);
}
foo(1,2);
foo.apply({n: 5}, [1, 2]);

三、call方法

自行设置绑定对象,传入参数用逗号隔开。

function foo(x, y) {
    console.log('结果' ,x+y);
    console.log('绑定对象', this);
}
foo(1,2);
foo.call({m: 55}, 11, 22);

posted @ 2020-04-26 18:09  见嘉于世  阅读(849)  评论(0编辑  收藏  举报