#目的
- クラスのメソッド内で、メソッドを呼び出したい時にうまく呼び出せない事象を解決する
##結論
- 今後、"this"を使いたい時は、具体的に何を指しているか確認すること。
#今回やること
多次元データに対して、クラス内でメソッドを使います。
ポケモンが格納されているデータは、こんな感じ。(1匹分)
これが245匹分ある。
(() => {
window.allPokemon = [{
"Number": "001",
"Name": "Bulbasaur",
"Generation": "Generation I",
"About": "Bulbasaur can be seen napping in bright sunlight. There is a seed on its back. By soaking up the sun's rays, the seed grows progressively larger.",
"Types": [
"Grass",
"Poison"
],
"Resistant": [
"Water",
"Electric",
"Grass",
"Fighting",
"Fairy"
],
"Weaknesses": [
"Fire",
"Ice",
"Flying",
"Psychic"
],
"Fast Attack(s)": [{
"Name": "Tackle",
"Type": "Normal",
"Damage": 12
},
{
"Name": "Vine Whip",
"Type": "Grass",
"Damage": 7
}
],
"Special Attack(s)": [{
"Name": "Power Whip",
"Type": "Grass",
"Damage": 70
},
{
"Name": "Seed Bomb",
"Type": "Grass",
"Damage": 40
},
{
"Name": "Sludge Bomb",
"Type": "Poison",
"Damage": 55
}
],
"Weight": {
"Minimum": "6.04kg",
"Maximum": "7.76kg"
},
"Height": {
"Minimum": "0.61m",
"Maximum": "0.79m"
},
"Buddy Distance": "3km (Medium)",
"Base Stamina": "90 stamina points.",
"Base Attack": "118 attack points.",
"Base Defense": "118 defense points.",
"Base Flee Rate": "10% chance to flee.",
"Next Evolution Requirements": {
"Amount": 25,
"Name": "Bulbasaur candies"
},
"Next evolution(s)": [{
"Number": 2,
"Name": "Ivysaur"
},
{
"Number": 3,
"Name": "Venusaur"
}
],
"MaxCP": 951,
"MaxHP": 1071
},
##実装(うまくいっていない)
(() => {
window.pokemonager = {
findNames: (array = allPokemon) => {
return array.map(pokemon => pokemon.Name)
},
findByResistance: (attack) => {
return allPokemon.filter((pokemon) => {
return pokemon.Resistant.includes(attack)
})
},
findNamesByResistance: (attack) => {
const a = this.findByResistance(attack)
const b = this.findNames(a)
return b;
},
###だいたいこうなる
試行錯誤の結果だいたいこうなる。
is not defined
もしくは
is not function
##学び
thisの親は?
->アロー関数である
つまり、thisは findNamesByResistance自体を呼んでいる!!
完 全 理 解 !
(オブジェクトを呼んでいるつもりだった)
##実装
(() => {
window.pokemonager = {
findNames: (array = allPokemon) => {
return array.map(pokemon => pokemon.Name)
},
findByResistance: (attack) => {
return allPokemon.filter((pokemon) => {
return pokemon.Resistant.includes(attack)
})
},
findNamesByResistance: function (attack) {
const a = this.findByResistance(attack)
const b = this.findNames(a)
return b;
},
```