`

object 面向对象编程

阅读更多

在java编程过程中,经常需要将前端的json数据传递到后端,比如写入数据库。一般的ibatis都会将java对象映射到数据库结构,从而方便的进行数据库操作。但如何更好的将前端数据和java对象对应起来呢。

 

这个时候我们想到了js中的object对象,可以设置属性和方法

1. 创建对象的实例

personObj=new Object()
personObj.firstname="John"
personObj.lastname="Doe"
personObj.age=50
personObj.eyecolor="blue"
 

2. 创建对象的模版

模版定义了对象的结构。

function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname
this.lastname=lastname
this.age=age
this.eyecolor=eyecolor
}
 注意:模版仅仅是一个函数。你需要在函数内部向 this.propertiName 分配内容。

一旦拥有模版,你就可以创建新的实例,就像这样:

myFather=new person("John","Doe",50,"blue")
myMother=new person("Sally","Rally",48,"green")

 同样可以向 person 对象添加某些方法。并且同样需要在模版内进行操作:

function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname
this.lastname=lastname
this.age=age
this.eyecolor=eyecolor
this.newlastname=newlastname
}

 注意:方法只是依附于对象的函数而已。然后,我们需要编写 newlastname() 函数:

function newlastname(new_lastname)
{
this.lastname=new_lastname
}
 Newlastname() 函数定义 person 的新的 lastname,并将之分配给 person。通过使用 “this.”,JavaScript 即可得知你指的 person 是谁。因此,现在你可以这样写:myMother.newlastname("Doe")。

 

参考:

http://www.w3school.com.cn/js/js_objects.asp

http://json.org/js.html

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics