JS / jQuery对象

时间:2013-03-09 10:23:57

标签: javascript jquery

我正在编写一个简单的通知系统,但我只是在学习JS / jQuery(前端对我来说是新的)而且我有问题。 我写了以下代码:

 (function ($) {

    var notification = function(title, msg, duration) {
        this.element = $('<div class="notification"><h3>' + title + '</h3><div class="notification_body">' + msg + '<br/><i>(для скрытия уведомления кликните здесь два раза)</i></div></div>');
        this.element.dblclick(notification.hide);
        $('#notifications_bar').prepend(this.element.hide().fadeIn(1000));
    }

    notification.hide = function() {
        var $this = this;
        this.element.fadeOut(1000, function () {
            $this.element.remove();
        })
    }

    $.extend({
        notify: function(title, msg, duration) {
            return new notification(title, msg, duration);
        }
    });
})
    (jQuery);

但方法notification.hide中存在错误:this.element未定义。 你能解释一下我的错误吗? 谢谢。

1 个答案:

答案 0 :(得分:4)

当您直接传递 附加到对象的函数时,函数会忘记它附加到哪个对象(因此this的值变化)。这是因为在调用函数之前, this 的值不会被解析。

相反,使用您用于fadeOut函数的相同方法(存储对this的引用,并在匿名函数中使用它;

var $this = this;
this.element.dblclick(function () {
    $this.hide();
});

或者,您可以使用jQuery.proxy()Function.prototype.bind()(仅限ES5兼容浏览器)强制函数this的值,无论以后将其附加到何处:< / p>

this.element.dblclick(jQuery.proxy(notification.hide, this));