views:

20

answers:

1

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:

  1. Send string from web service like new Person('cem','1000','15000')
  2. eval the string on client side like:

    dataType:json, success:function(msg){ globalObj = eval(msg.d); },

  3. 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...?

+1  A: 

It's not possible in ECMA-/Javascript to "overload" a method/function like this.

A good workaround is to check the arguments object, like

function Person(){
   if(typeof arguments[0] === 'object'){
      // addional checks 
      this.Name   = arguments[0].Name;
      this.Salary = arguments[0].Salary;
      // etc.
   }
   else if(arguments.length === 2){
      this.Name   = arguments[0];
      this.Salary = arguments[1];
      // etc.
   }
}

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 json string into a javascript object anyway. That can be done by using window.JSON.parse(<jsonstring>) in "modern" browsers. Older browsers (like IE7) need the json2.js from www.json.org to offer the same functionality.

jAndy