开发者

How to bind functions to the JSON object?

function Person(_name, _id, _salary){
    this.Name = _name;
    this.Id = _id;
    this.Salary = _salary;
}

Person.prototype.f_IncreaseSalary = function( _percentage ){
    this.Salary *= _percentage;
}

var per = new Person("cem",10,15000);

1) I can access to per.f_IncreaseSalary(0.2) but what if i create this object from JSON string how can i access f_IncreaseSalary function?

var sPer = {"Person" : {"Name":"Cem", "Id":10, "Salary":15000} };
sPer.f_IncreaseSala开发者_如何学Cry(0.2); // it won't! 

2) How can i create sPer object which has functions of Person class?

3) How can i understand sPer has f_IncreaseSalary function?


Your Person prototype and the JSON object which has a property Person are completely unrelated. You'll need to explicitly create a new object with new Person(...) and the data from the JSON object:

var sPer = {"Person" : {"Name":"Cem", "Id":10, "Salary":15000} };
var per = new Person(sPer.Person.Name, sPer.Person.Id, sPer.Person.Salary);
per.f_IncreaseSalary(0.2);


The object literal you are creating is not a Person object. It is an unnamed object with the property 'Person' that has properties that are the same as your person object.

var personData = sPer.Person;
var p = new Person( personData.Name, personData.Id, personData.Salary);
p.f_IncreaseSalary(0.2)


To answer your question:

JSON is an acronym of Javascript Object Notation, which basically, once you create an object from a JSON String, you have an object with properties.

So for your example,

var sPer = {"Person" : {"Name":"Cem", "Id":10, "Salary":15000} };

You are creating an object literal which is not identical to your Person object (that you declared). Your sPer basically allows you to do this...

//Changing values in Javascript;

sPer.Salary = 100000;
sPer.Name = "John";
sPer.Id = 200;

It won't have the function:

Person.prototype.f_IncreaseSalary = function( _percentage ){
    this.Salary *= _percentage;
}

As you cannot create functions in JSON.

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜