適切なコンテキストで関数を呼び出したいとします。そのためにはFunction#call
があります。また、通常の関数を使用する必要があります。「太い矢印」関数はthis
の扱いが異なります。
var addClass = function (className) {
if (this.classList.contains(className)) {
this.classList.remove('active');
this.classList.add(className);
} else {
this.classList.add(className);
}
}
exploreStory_buttons.forEach(el => {
el.addEventListener('mouseover'); // where is the event listener??
addClass.call(this, active); // N.B. active is undefined here. Do you mean "active"?
});
「スマート」コードを書くために言語機能を悪用したくない場合もあります。複数の文に対してif/elseと複数行を使用すると、コード難読化プログラムではありません。あなたは「ホバー」動作を追加したいと仮定すると、
、コードは次のようになり何かだろう:
function addClass(className) {
return function() {
this.classList.add(className);
}
}
function removeClass(className) {
return function() {
this.classList.remove(className);
}
}
var activate = addClass('active');
var deactivate = removeClass('active');
exploreStory_buttons.forEach(el => {
el.addEventListener('mouseenter', activate);
el.addEventListener('mouseleave', deactivate);
});
注意をどのようにイベントハンドラとして機能することができaddClass
とremoveClass
リターン機能。変数をactivate
とdeactivate
という変数に格納するということは、ループ内に複数の等価な関数のコピーを作成していないことを意味しますが、実際にはすべての要素に同じ関数を割り当てます。
activate
/deactivate
変数や関数を返す関数hover()
機能を実装することで回避することができます(jQueryのsimilar featureを持っている):
function hover(elements, onenter, onleave) {
elements.forEach(el => {
el.addEventListener('mouseenter', onenter);
el.addEventListener('mouseleave', onleave);
});
}
hover(exploreStory_buttons, function() {
this.addClass('active');
}, function() {
this.removeClass('active');
});
ここでは、イベントハンドラ関数は一度だけと直接作成されていますどこに必要なのですか?それらをヘルパー変数に格納するよりもずっと優れています。
'addClass(アクティブ)' 'active'したがって、関数に渡すパラメータが定義されていない、未定義の変数です。 ''アクティブ ''でなければなりません。 –
@ JeremyThille私は実際にはパラメータ括弧内にアクティブな引用符を入れようとしていましたが、うまくいきませんでした。 – cpsavante
BTW '&'はビット単位の演算子ですから、おそらく短絡操作のために '&&'を意味しています。それ以外に同じクラスを追加する理由は何ですか? – Redu