ECMAScript 面向对象技术:创建你自己的对象

在javascript中创建新的对象有几种方法:

1. 直接创建一个对象的实例

下面的代码创建了一个新的实例,然后添加了四个属性:

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

或者你也可以这样直接创建一个实例

 

 personObj={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"};

 

给personObj添加一个方法也很简单.下面的代码给personObj添加了一个eat()方法

personObj.eat=eat;

eat = function() {

  //do something 

2. 创建一个构造器

创建一个function生成对象

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

在function内部你需要指定赋值给属性名,使用this给所有属性的原因是因为你将一次有多个person实例(你要处理哪个person必须清楚)。this就是当前正在处理person的实例。

一旦你有对象构造器,你可以创建新的对象实例,像这样 

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

你也可以添加一些方法给这个对象构造器,你一样可以在function内部完成 

function person(firstname,lastname,age,eyecolor) 

{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;

this.newlastname=newlastname;
}

注意这些方法仅仅是附加到objects上的,我们需要实现这个newlastname() 方法;

function newlastname(new_lastname)
{
this.lastname=new_lastname;
}
newlastname() 方法定义了person's 新的last name 和指定给这个person。 通过this关键字,javascript知道你要指定给哪个person。现在你可以这样写

 

myMother.newlastname("Doe") 

 

假如你现在想在你的对象构造器中添加另一个方法,你又不想改变上面的代码,你可以这样做

 person.prototype.eat = function() {  

  //do somethng

}

posted on 2011-12-07 18:38  大浩子  阅读(330)  评论(0编辑  收藏  举报

导航