admin管理员组文章数量:1414604
I have object myObject
, inside I have function execute()
, inside I have $.ajax({
which have plete: function(xmlHttp){
. Inside that function I want to call setResult which is defined in the myObject
. How to do that?
function myObject() {
this.setResult = setResult;
function setResult(result) {
this.result = result;
}
function execute() {
$.ajax({
plete: function(xmlHttp){
(?) setResult(jQuery.parseJSON(xmlHttp.responseText));
}
});
}
I have object myObject
, inside I have function execute()
, inside I have $.ajax({
which have plete: function(xmlHttp){
. Inside that function I want to call setResult which is defined in the myObject
. How to do that?
function myObject() {
this.setResult = setResult;
function setResult(result) {
this.result = result;
}
function execute() {
$.ajax({
plete: function(xmlHttp){
(?) setResult(jQuery.parseJSON(xmlHttp.responseText));
}
});
}
Share
Improve this question
asked Mar 11, 2012 at 19:37
svenkapudijasvenkapudija
5,16615 gold badges71 silver badges99 bronze badges
2 Answers
Reset to default 6The standard way to do OOP is to use myObject
as a constructor, and extend its prototype
object with whatever needs to be inherited.
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"
plete: 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 mon.
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 plete:
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.
jQuery's $.ajax
method gives you a context:
property that lets you set the calling context of the callbacks, as I've shown above.
function myObject() {
var that = this; // Reference to this stored in "that"
this.setResult = setResult;
function setResult(result) {
this.result = result;
};
function execute() {
$.ajax({
plete: function(xmlHttp){
that.setResult(jQuery.parseJSON(xmlHttp.responseText));
}
});
}
Also you can check out jquery proxy and/or bind
本文标签: JavaScript OOP with jQueryStack Overflow
版权声明:本文标题:JavaScript OOP with jQuery - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745193637a2647031.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论