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);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM