js创建对象

转自: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")。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值