JavaScript 对象

本文讨论几种js创建对象的方法,先从最好理解
1、工厂模式开始:

<script text="javascript">
function createPerson(name,age,job){
var o =new Obeject();
o.name = name;
o.age = age;
o.job = job;
o.sayName = function(){
alert(this.name);
};
return o;
}

var tanya = createPerson("tanya","30","female");
var ansel = createPerson("ansel","30","male");
tanya.sayName();
ansel.sayName();
</script>

2、对象模式称为构造函数模式

<script text="javascript">
//执行第一句代码前,js引擎会为我们生成一个对象
function Person(name,age,job){
this.name = name;
this.age = age;
this.job = job;
this.sayName = function(){
alert(this.name);
};
//此处有一个隐藏的return语句,用于将之前生成的对象返回。
}
var tanya = new Person("tanya","30","female");
var ansel = new Person("ansel","30","male");
tanya.sayName();
ansel.sayName();
</script>

3、原型模式

<script text="javascript">
function Person(){}

Person.prototype.name = name;
Person.prototype.age = age;
Person.prototype.job = job;
Person.prototype.sayName = function(){
alert(this.name);
};

var person = Person();
var person2 = Person();
</script>

如果使用原型对象方式,那么生成的所有对象会共享原型中的属性,这样一个对象改变了该属性也会反映到其他的对象当中。
4、使用原型+构造函数方式来定义对象

<script text="javascript">
function Person(name,age,job){
this.name = name;
this.age = age;
this.job = job;
}
Person.prototype.sayName= function(){
alert(this.name);
};
var tanya = new Person("tanya","30","female");
var ansel = new Person("ansel","30","male");
tanya.sayName();
ansel.sayName();
</script>

使用原型+构造函数方式来定义对象,对象之间的属性互不干扰,各个对象间共享同一个方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值