I have a Person javascript class like
function Person(_name, _id, _salary){
this.Name = _name;
this.Id = _id;
this.Salary = _salary;
}
First, i want to overload constructor function with:
function Person( _person ){
this.Name = _person.Name;
this.Salary = _person.Salary;
this.Id = _person.Id;
}
But whatever i do, it goes to the first function …!?
Second, i have some functions for this javascript class like:
Person.prototype.f_IncreaseSalary = function( _percentage ){
this.Salary *= _percentage;
}
What i am doing now is:
- Send string from web service like
new Person('cem','1000','15000') -
eval the string on client side like:
dataType:json,
success:function(msg){
globalObj = eval(msg.d);
}, - and use the javascript object with its functions.
globalObj.f_IncreaseSalary(0.2);
But i think i should return the string within json, like:
"Person" : {"name":"Cem", "id":1000, "salary":15000 }
How can i bind the javascript methods of the Person classs to the json object…?
It’s not possible in ECMA-/Javascript to “overload” a method/function like this.
A good workaround is to check the arguments object, like
I don’t think I understand your second question, “how to bind the javascript methods to a json object”.
You would need to “parse” the
jsonstring into a javascript object anyway. That can be done by usingwindow.JSON.parse(<jsonstring>)in “modern” browsers. Older browsers (like IE7) need thejson2.jsfrom http://www.json.org to offer the same functionality.