Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/436.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cassandra/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何编写oopjs并同时使用jQuery_Javascript_Jquery_Oop - Fatal编程技术网

Javascript 如何编写oopjs并同时使用jQuery

Javascript 如何编写oopjs并同时使用jQuery,javascript,jquery,oop,Javascript,Jquery,Oop,通常(如果不总是),当jQuery允许您向某些JS事件(如click)添加回调时,在回调函数中,它们将this的“含义”更改为触发事件的DOM元素 这可能非常有用,但当您使用js编写OOP代码时,它会妨碍您: 在本例中,this.test()将不起作用,因为this不再是MyClass上的一个实例,而是一个jQuery DOM元素(span) 我的问题是:有没有一种方法可以继续使用这种模式在JS中编写OOP代码,同时使用jQuery?还有:当jQuery可以像第一个参数一样轻松地发送jQuery

通常(如果不总是),当jQuery允许您向某些JS事件(如click)添加回调时,在回调函数中,它们将
this
的“含义”更改为触发事件的DOM元素

这可能非常有用,但当您使用js编写OOP代码时,它会妨碍您:

在本例中,
this.test()
将不起作用,因为
this
不再是
MyClass
上的一个实例,而是一个jQuery DOM元素(span)

我的问题是:有没有一种方法可以继续使用这种模式在JS中编写OOP代码,同时使用jQuery?还有:当jQuery可以像第一个参数一样轻松地发送jQuery DOM元素时,为什么它要在回调函数中更改此

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");
    }
}
创建实例时,该实例将获得自己的
。单击的
函数将在原型中隐藏通用实例。会的
始终使用相同的
绑定,无论您如何调用它。因此,您可以传递
此参数。在所有位置单击
并使其工作。

像这样,jQuery也通过
e.currentTarget
发送DOM元素,其中
e
是作为第一个参数发送的事件对象jQuery不会更改任何内容。每当绑定事件处理程序时,
这个
引用DOM元素(不幸的是,它不在IE的
附件
中)。这与jQuery无关(当然jQuery会强制执行它,以便在IE中工作)。看。可能是和的副本。@Esailija谢谢,这真的很有帮助!这不是最简单的方法,但它只需要很少的重写。@Nicolaseurdu是的,它没有语言支持,所以你必须用所有这些
$来模拟静态绑定。代理/函数#绑定
样板垃圾
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");
    }
}