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
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745193638a4615984.html
评论列表(0条)