I’m writing the javascript on FireFox 11 with a text editor. In the follow case, “var n=this.val” becomes “undefined”. How to get the local value in the original class object?
<html>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
var Test = {
val : 0,
begin: function(v){
this.val = v;
this.recieve();
},
complete: function(o){
var n = this.val; // undefined
},
recieve : function(){
$.ajax({
url : "http://www.yahoo.com/", // Dummy
type: "POST",
dataType: "json",
complete: this.complete,
timeout: 1000,
});
},
};
var c = Object(Test);
c.begin(10);
</script>
</body>
</html>
Because
completeis a callback the scope has changed andthisdoesn’t refers to the object calledTest. You only need to replacethiswithTestin thecompletefunction:=== UPDATE ===
Your question was “How to get the local value in the original class object?”. My answer shows you how to get the field of your static object.
If you need a shared object you should change the structure to:
Now you can create two different objects: