转自:http://www.w3school.com.cn/js/js_objects.asp
1. 创建对象的实例
下列代码创建了一个对象的实例,并向其添加了四个属性:
personObj=new Object()
personObj.firstname="John"
personObj.lastname="Doe"
personObj.age=50
personObj.eyecolor="blue"
向 personObj 添加方法也很简单。下列代码向 personObj 添加了名为 eat() 的方法:
personObj.eat=eat
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")。
1. 创建对象的实例
下列代码创建了一个对象的实例,并向其添加了四个属性:
personObj=new Object()
personObj.firstname="John"
personObj.lastname="Doe"
personObj.age=50
personObj.eyecolor="blue"
向 personObj 添加方法也很简单。下列代码向 personObj 添加了名为 eat() 的方法:
personObj.eat=eat
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")。