- Mastering JavaScript Functional Programming
- Federico Kereki
- 255字
- 2021-07-02 22:41:14
Working with methods
There is, however, a case you should be aware of: what happens if you are calling an object's method? If your original code had been something along the lines of:
fetch("some/remote/url").then(function(data) {
myObject.store(data);
});
Then the seemingly obvious transformed code would fail:
fetch("some/remote/url").then(myObject.store);
Why? The reason is that in the original code, the called method is bound to an object (myObject) but in the modified code, it isn't bound, and it is just a free function. We can then fix it in a simple way by using bind() as:
fetch("some/remote/url").then(myObject.store.bind(myObject));
This is a general solution. When dealing with a method, you cannot just assign it; you must use .bind( so the correct context will be available. Code like:
function doSomeMethod(someData) {
return someObject.someMethod(someData);
}
Should be converted to:
const doSomeMethod = someObject.someMethod.bind(someObject);
Read more on .bind() at https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind.
This looks rather awkward, and not too elegant, but it's required so the method will be associated to the correct object. We will see one application of this when we promisify functions in Chapter 6, Producing Functions - Higher-Order Functions. Even if this code isn't so nice to look at, whenever you have to work with objects (and, remember, we didn't say that we would be trying to aim for fully FP code and that we would accept other constructs if they made things easier) you'll have to remember to bind methods before passing them as first-class objects, in pointfree style.
- Unreal Engine Physics Essentials
- The DevOps 2.3 Toolkit
- 零基礎(chǔ)搭建量化投資系統(tǒng):以Python為工具
- Mastering Objectoriented Python
- PHP 7底層設(shè)計與源碼實現(xiàn)
- Vue.js入門與商城開發(fā)實戰(zhàn)
- Java開發(fā)入行真功夫
- Mastering C# Concurrency
- 云計算通俗講義(第3版)
- 人人都懂設(shè)計模式:從生活中領(lǐng)悟設(shè)計模式(Python實現(xiàn))
- Visual C#.NET程序設(shè)計
- Extending Puppet(Second Edition)
- 軟件測試實用教程
- 常用工具軟件立體化教程(微課版)
- Java Web從入門到精通(第3版)