In a page I create an instance of a class (MyClass), this class has 2 methods. But I’d like to do 2 things :
- In (1), set the value
this.message - In (2), call the information method or another method of the class
Thank,
<script type="text/javascript">
$(document).ready(function () {
var myClass = new MyClass("MyParam");
$('#Target').click(function (event) {
myClass.save("Test");
});
});
</script>
function MyClass(myParam) {
this.myParam = myParam;
this.isError = false;
this.message = "";
}
// Define the class methods.
MyClass.prototype = {
save: function (action) {
**(2)**
},
information: function (action) {
**(1)**
}
};
Update1
When I execute the code below the data value in information is show as undifined
MyClass.prototype = {
click: function (action) {
var myData;
$.post(....., $("form").serialize(),
function (data) {
myData = data;
});
this.isError = this.information(myData);
},
information: function (data) {
alert(data);
return true;
}
};
Inside the
saveandinformationfunctions,thisshould be the currentMyClassobject.So, inside
save,this.messageshould work, and insideinformation,this.save()should work.UPDATE:
$.postis an AJAX request and is ran asynchronously. Meaning thatthis.isError = this.information(myData);is ran before it finishes, thereforemyDataisundefined. You need to callthis.informationfrom inside the callback.Inside the callback,
thiswill no longer be yourMyClassobject, so we need to save a reference to it. Like this: