[英]JavaScript OOP with jQuery
I have object myObject
, inside I have function execute()
, inside I have $.ajax({
which have complete: function(xmlHttp){
. Inside that function I want to call setResult which is defined in the myObject
. How to do that? 我有对象
myObject
,内部有函数execute()
,内部有$.ajax({
其中具有complete: function(xmlHttp){
。在该函数内部,我想调用在myObject
定义的setResult。 ?
function myObject() {
this.setResult = setResult;
function setResult(result) {
this.result = result;
}
function execute() {
$.ajax({
complete: function(xmlHttp){
(?) setResult(jQuery.parseJSON(xmlHttp.responseText));
}
});
}
The standard way to do OOP is to use myObject
as a constructor, and extend its prototype
object with whatever needs to be inherited. OOP的标准方法是使用
myObject
作为构造函数,并使用需要继承的内容扩展其prototype
对象。
function myObject() {
// constructor function
}
myObject.prototype.setResult = function (result) {
this.result = result;
}
myObject.prototype.execute = function() {
$.ajax({
context: this, // bind the calling context of the callback to "this"
complete: function(xmlHttp){
this.setResult(jQuery.parseJSON(xmlHttp.responseText));
}
});
}
var obj = new myObject();
obj.execute();
There's no requirement that it be done this way, but it's very common. 有没有要求它做这种方式,但它是很常见的。
You need to keep in mind that the calling context of a function varies based on how that function is called. 您需要记住,函数的调用上下文根据函数的调用方式而有所不同。 With respect to the
complete:
callback, jQuery sets the context, so it won't be your object unless you tell jQuery to make it that object or use some other way to bind the context . 关于
complete:
回调,jQuery设置上下文,因此除非您告诉jQuery使它成为该对象或使用其他方式绑定上下文 ,否则它不会成为您的对象。
jQuery's $.ajax
method gives you a context:
property that lets you set the calling context of the callbacks, as I've shown above. jQuery的
$.ajax
方法为您提供了context:
属性,该属性使您可以设置回调的调用上下文,如上所示。
function myObject() {
var that = this; // Reference to this stored in "that"
this.setResult = setResult;
function setResult(result) {
this.result = result;
};
function execute() {
$.ajax({
complete: function(xmlHttp){
that.setResult(jQuery.parseJSON(xmlHttp.responseText));
}
});
}
Also you can check out jquery proxy and/or bind 您也可以签出jquery代理和/或绑定
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.