ga('set', 'anonymizeIp', 1);

[Javascript] 匿名箭頭函數與$(this)的限制用法

Share

Javascript在ES6有箭頭函數的用法,箭頭函數有其使用限制,本文討論箭頭函數的使用限制及特性,並舉例說明。

箭頭函數

箭頭函數沒有自己的thisargumentssuper等語法。

箭頭函數 之 我沒有this

這邊舉個例子,如果你想要製作動態list按鈕,讓按鈕按下後addClass,其他的按鈕removeClass,你又沒有使用react、vue等框架且又不想寫太多行程式碼時,可以參考以下方法。

HTML

其中須注意有引入jQuery使用。

CSS

div.listitem {
    height: 60px;
    margin: 0;
    padding: 10px;
    background-color: grey;
    color: black;
    cursor: pointer;
    border-width: 1px;
    text-align: center;
}

div.listitem:hover {
    color: white;
}

div.active {
    color: red;
    border-left: 2px;
    border-left-style: solid;
}

這邊的樣式,是讓listitem這個class文字為黑色,滑鼠懸浮時文字為白色,在active狀態時文字為紅色。

JS – view.js 建構畫面UI


在body建構listitem。

JS – renderer.js

// 點擊listitem將除了本身外的listitem都移除active class,並將自己加上active class。
 itemOnClick() {
    $(this).siblings('.listitem').removeClass('active');
    $(this).addClass('active');
}

// 擁有listitem class的元素在click時呼叫[itemOnClick]函式
$(document).on('click', '.listitem', itemOnClick);

以上可以實現動態按鈕的效果。

解析 – itemOnClick函式

在上面itemOnClick這個不使用箭頭函數的原因就是函式內部會用到$(this),所以我們使用原本的宣告。
若使用箭頭函式如下宣告:

let itemOnClick = () => {
    $(this).siblings('.listitem').removeClass('active');
    $(this).addClass('active');
}

就會抓不到$(this)。

Jys

Published by
Jys

Recent Posts

[python] Flask Create RESTful API

This article gi... Read More

2 年 前發表

[Javascript] 新增/刪除JSON中key值

在web訊息交換常會需要對JS... Read More

2 年 前發表

[JAVA] SQL Server Connection

本文介紹JAVA連線SQL s... Read More

3 年 前發表

[python] 檔案整理 – 整理影片檔長度資訊存入excel

本文介紹如何使用python寫... Read More

3 年 前發表