Popular Posts
Asynchronous and deferred JavaScript execution explained Normal execution <script> This is the default behavior of the <script> element. Parsing of the HTML code pauses while the scr... Statement.executeBatch() always returns an array of value -2 The elements in the array returned by the method executeBatch may be one of the following: A number greater than or equal to zero -- indi... vi hot key guide 第一部份:一般模式可用的按鈕說明,游標移動、複製貼上、搜尋取代等 移動游標的方法 h 或 向左方向鍵(←) 游標向左移動一個字元 j 或 向下方向鍵(↓) 游標向下移動一個字元 k 或 向上方向鍵(↑) 游標向上移動一個字元 l 或 向右方向鍵(→) 游標...
Stats
Javascript lambda: No binding of this
<form>
    <p>
        <button id="f1">Invoke with function</button>
    </p>
    <p>
        <button id="f2">Invoke with lambda</button
    </p>
    <div id="output"></div>
</form>
<script>
    'use strict';
    (function () {
        let f1 = document.querySelector('#f1'),
            f2 = document.querySelector('#f2'),
            output = document.querySelector('#output');

        function appendResult(message) {
            let log = document.createElement('pre');
            log.appendChild(document.createTextNode(message));
            output.appendChild(log);
        }

        // define with function, reference 'this' to button element
        f1.onclick = function () {
            appendResult('Button [Invoke with function] clicked!');
            appendResult('This is: ' + JSON.stringify(this) + ' [' + this.constructor.name + ']');
            console.log(this);
            return false;
        };

        // define with lambda, reference 'this' to {name: 'Bruce'} object
        f2.onclick = () => {
            appendResult('Button [Invoke with lambda] clicked!');
            appendResult('This is: ' + JSON.stringify(this) + ' [' + this.constructor.name + ']');
            console.log(this);
            return false;
        };

    }).call({name: 'Bruce'})
</script>
Result:

Reference: No binding of this
Memo: Debounce Task

To prevent multi-execution from caller in short time, use debounce for single execution.

var debounce = function (func, threshold, execAsap) {
    var timeout;
    return function debounced () {
        var obj = this, args = arguments;
        function delayed () {
            if (!execAsap)
            func.apply(obj, args);
            timeout = null;
        };
        if (timeout)
            clearTimeout(timeout);
        else if (execAsap)
            func.apply(obj, args);
        timeout = setTimeout(delayed, threshold || 100);
    };
}