javascriptのコールバックとbind
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// (u.js) 'use strict'; module.exports = { p(a) { console.log(a); }, foreach(obj, func) { for (const key of Object.keys(obj)) { const value = obj[key]; func(key, value); } }, dispKeyValue(k, v) { this.p(k + " => " + v); } }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// (main.js) const u = require('./u'); const taro = { phrase: "こんにちは", name: "たろう", age: 19, greeting() { p(this.phrase + ", " + this.name + "(" + this.age + ")です。"); }, }; // u.foreach(taro, u.dispKeyValue); // TypeError: Cannot read property 'p' of undefined u.foreach(taro, u.dispKeyValue.bind(u)); |
1 2 3 4 5 6 |
phrase => こんにちは name => たろう age => 19 greeting => greeting() { p(this.phrase + ", " + this.name + "(" + this.age + ")です。"); } |