如何使用'this'关键字创建函数引用

时间:2011-08-30 06:18:04

标签: javascript

我正在创建一个小工具提示应用程序,但我遇到了麻烦。我正在尝试向文档添加事件,但是在引用需要执行的功能时遇到了问题。这是代码:

var Note, note;
(function () {
    'use strict';

    // Helper functions
    function addEvent(to, type, fn) {
        if (to.addEventListener) {
            to.addEventListener(type, fn, false);
        } else if (to.attachEvent) {
            to.attachEvent('on' + type, fn);
        } else {
            to['on' + type] = fn;
        }
    }

    // Temporary constructor
    function Temp() {
        this.dragging = false;

        return this;
    }

    Temp.prototype = {
        listen: function () {
            this.dragging = true;
        },
        drag: function () {
            alert('hi 1');
            if (!this.dragging) return;
            alert('hi 2');
        },
        create: function () {
            // unimportant code ...

            addEvent(document, 'mousedown', this.drag);

            // unimportant code ...
        }
    };

    window.Note = Temp;
}());

note = new Note();
note.create(); // the note is created as planned
note.listen(); // alert(note.dragging) yields true

如果代码中存在小错误,我认为这些都不是问题,我系统上的代码会传递JSLint(我知道这并不能保证正确性)。这两个警报都没有提醒他们的论点;但我怀疑,问题是将'this.drag'指定为事件处理程序的函数引用。有没有解决方法呢?

谢谢大家的时间!

1 个答案:

答案 0 :(得分:1)

尝试下一步:

(function () {
    'use strict';

// Helper functions
function addEvent(to, type, fn) {
    if (to.addEventListener) to.addEventListener(type, fn, false);
    else if (to.attachEvent) to.attachEvent('on' + type, fn);
    else to['on' + type] = fn; // this is bad. this do not support multiple handlers
}

// Temporary constructor
function Temp() {
    this.dragging = false;
}

Temp.prototype = {
    constructor: Temp, // needed because it is removed when used Temp.prototype={...}
    listen: function () {
        this.dragging = true;
    },
    drag: function () {
        alert('hi 1');
        if (!this.dragging) return;
        alert('hi 2');
    },
    create: function () {
        //addEvent(document, 'mousedown', this.drag);
        addEvent(document, 'mousedown', this.drag.bind(this));
        // or in older maner (when .bind() not implemented):
        //var self=this;
        //addEvent(document, 'mousedown', function(){self.drag();});
    }
};

window.Note = Temp;
})();

var note = new Note();
note.create(); // the note is created as planned
note.listen(); // alert(note.dragging) yields true