简体   繁体   English

如何编写OOP JS并同时使用jQuery

[英]How to write OOP JS and use jQuery at the same time

Usually (if not always), when jQuery allows you to add a callback to some JS event like click, in the callback function they change the "meaning" of this into the DOM element which triggered the event. 通常(如果不总是),当jQuery的可以让你的回调添加一些JS事件一样点击,在回调函数,他们改变的“意义” this将触发事件的DOM元素。

This can be quite useful, but it will stand in your way when you write OOP code in js, like in this example : 这可能非常有用,但是当你在js中编写OOP代码时,它会阻碍你, 就像在这个例子中一样

function MyClass() {}

MyClass.prototype = {

    init: function() {
        $("#someSpan").click(this.doSomething);
    },

    doSomething: function() {
        alert("Here 1");
        this.test();
        return false;
    },

    test: function() {
        alert("Here 2");
    }
}

In this example, this.test() will not work, because this is not anymore an instance on MyClass but instead a jQuery DOM element (the span). 在这个例子中, this.test()将不起作用,因为this不再是MyClass上的实例,而是jQuery DOM元素(span)。

My questions are: is there a way to continue writing OOP code in JS using this pattern and also use jQuery? 我的问题是:有没有办法继续使用这种模式在JS中编写OOP代码并使用jQuery? And: why is jQuery changing this in the callback function when it could as easily send the jQuery DOM element as first argument ? 和:为什么jQuery的改变this回调函数时,它可以容易地把jQuery的DOM元素作为第一个参数?

jQuery has $.proxy that can be used like so: jQuery有$.proxy可以像这样使用:

function MyClass() {
    this.clicked = $.proxy(this.clicked, this);
}

MyClass.prototype = {

    clicked: function(e) {
        alert("Here 1");
        this.test();
        e.currentTarget; //this replaces "this"-the keyword used in "non OOP" contexts
//see http://api.jquery.com/event.currentTarget/
    },

    init: function() {
        $("#someSpan").click(this.clicked);
    },

    test: function() {
        alert("Here 2");
    }
}

When you create an instance, that instance gets its own .clicked function that shadows the generic one in the prototype. 在创建实例时,该实例会获得自己的.clicked函数,该函数会.clicked原型中的通用函数。 It will always have same this binding no matter how you call it. 它总是有相同的this结合,无论你怎么称呼它。 So you can pass this.clicked all over the place and have it work. 因此,您可以将this.clicked传递this.clicked所有地方并让它工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM