Jquery插件私有数据和$(this)

时间:2012-07-05 12:13:50

标签: javascript jquery jquery-plugins

我正在开发一个JQuery插件,它将私有数据存储在对象的数据字段中(正如我发现的文章中所推荐的那样):

$.fn.awesomify = function (schema, data) {
    $(this).data('schema', schema);
}

然后我可以在私有方法中检索此值:

function rebuild() {
    var schema = $(this).data('schema');
}

现在我遇到的问题是,当从另一个对象调用该方法时,$(this)的值是不同的。例如,href的onclick事件:

var a = ...;
a.click(function () {
    rebuild(); // Now $(this) is the a-object
});

我该如何解决这个问题?

谢谢!

2 个答案:

答案 0 :(得分:2)

这是因为this的值是在调用时确定的,并且设置为方法所属的对象,如果方法没有附加到对象*,则设置为window; rebuild()未附加到对象,因此thiswindow

您可以将this的值作为参数传递,也可以使用Function.prototype.call / Function.prototype.apply方法;

rebuild.call(this);

或:

rebuild(this);

function rebuild(that) {
    var schema = $(that).data('schema');
}

* - >例外情况是,如果您在strict modeundefined,则此处不相关。

答案 1 :(得分:0)

您可以将“this”对象存储到某个变量中,然后在此变量可见的任何地方使用它

    var currentObj = $(this);

    function rebuild() {
       var schema = currentObj.data('schema'); 
    } 
相关问题