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

使用bind重新绑定对象。

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

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

二、apply方法

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

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

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

三、call方法

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

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

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

相关文章:

  • 2022-12-23
  • 2021-12-13
  • 2021-11-22
  • 2023-02-24
  • 2022-12-23
  • 2021-10-06
  • 2021-05-30
  • 2021-06-14
猜你喜欢
  • 2022-12-23
  • 2021-08-30
  • 2021-10-01
  • 2021-06-26
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案