JavaScript自定义对象的方式

来源:互联网 发布:jquery ajax json请求 编辑:程序博客网 时间:2024/05/22 02:15

在JavaScript中,对象是拥有属性和方法的数据。

自定义对象的方式:直接创建方式,对象初始化器方式,构造函数方式,原型模式,混合模式(原型+构造),动态方式,工厂方式

直接创建方式

<script type="text/javascript">var student=new Object();student.name="丹",student.age=21,student.sex="女",student.doHomework=function(){console.log("正在做作业");console.log(this.name+"正在做作业");}console.log(student.name);student.doHomework();</script>

对象初始化器方式

<script type="text/javascript">var student={name:"丹",age:21,sex:"女",doHomework:function(){console.log("正在做作业");console.log(this.name+"正在做作业");(this写在对象里边)}};console.log(student.name);student.doHomework();</script>

构造函数方式

1.

<script type="text/javascript">functionStudent(){        this.name="丹",        this.doHomework=function(){        console.log("正在做作业");                       console.log(this.name+"正在做作业");                }         }        varstudent = new Student();        student.doHomework();</script>
2.

<script type="text/javascript">function Student(){this.name="丹",this.doHomework=homework;}function homework(){console.log(this.name+"正在做作业");}var student = new Student();      student.doHomework();</script>

总结:

1、和上面两种方式对比,采用构造函数方式创建对象能够有效地节省代码

2、采用构造函数方式创建对象,this不能省略,这也是和普通函数的区别。

3、采用构造函数方式创建对象,第二种方式更可取,提高了代码的复用性。

prototype原型方法[ˈprəʊtətaɪp]

在声明一个新的函数以后,函数会有一个prototype的属性,通过该属性为对象添加属性和方法。(在JavaScript中,函数也是对象)

<script type="text/javascript">function Student(){}Student.prototype.name="丹丹";Student.prototype.age=22;Student.prototype.doHomeWork=function(){console.log(this.name+"正在做作业");};var student = new Student();student.doHomeWork();</script>

混合式(构造+原型)——最常用

构造函数定义对象属性,原型式定义对象方法 

<script type="text/javascript">function Student(){this.name="丹丹";this.age=22;}Student.prototype.doHomeWork=function(){console.log(this.name+"正在做作业");};var student = new Student();student.doHomeWork();</script>

构造函数方式便于动态为属性赋值,但是这种方式将方法也定义在了构造方法体中,使得代码比较杂乱;而原型式不便于为属性动态赋值,但是这种方式定义的属性和方法实现了分离,所以取长补短——构造方法定义对象属性,原型方式定义对象方法。

工厂模式

function Student(name, age, job){ var o = new Object();o.name = name; o.age = age;  o.sayName = function(){        alert(this.name);    }return o;}var student = new Student("dan",22);
动态方式

<script type="text/javascript">function Student(name, age){this.name = name;    this.age = age;    this.friends = ["嗯哼","哼嗯"];if(typeof this.sayName!="function"){    Student.prototype.sayName = function(){     alert(this.name);           }        }}var student = new Student("dan",22);student.sayName();</script>

 

 

 

 

0 0
原创粉丝点击