JS_对象创建的几种方式

来源:互联网 发布:网络架构是什么 编辑:程序博客网 时间:2024/05/16 05:26

一、组合使用构造器模式和原型模式:

<script type="text/javascript">window.onload=function(){var inputEles=document.getElementsByTagName("input");inputEles.item(0).onclick=function(){//属性使用构造函数模式进行初始化function Person(name,age,job){this.name=name;this.age=age;this.job=job;this.friends=["Nicholas","Court"];};//方法使用原型模式Person.prototype={constructor:Person,sayName:function(){alert(this.name);}};var person1 = new Person();var person2 = new Person();person1.friends.push("Baohan");alert(person1.friends+">>>"+person2.friends); //两个friends是不同的。};};</script>
二、动态原型模式:

对方法的创建使用动态原型模式,在构造函数里,如果该方法存在于对象中,则该方法不在原型中重写,否则,重写原型中的方法。

inputEles.item(1).onclick=function(){function Person(name,age,job){this.name=name;this.age=age;this.job=job;this.friends=new Array();if(this.sayName != "function"){Person.prototype.sayName=function(){alert(this.name);};}};};
注意:任何对象原型的修改都会影响到该类型所有实例对象,同时不能对象创建完毕后不能重写原型,否则会切断对象中原型指针和原型的连接。

三、寄生构造函数模式:除了使用new操作符创建对象外,其他的没有什么不同

四、稳妥构造函数模式:不使用this操作符


寄生构造函数模式和稳妥构造函数模式都使用了return操作符,类型与工厂方法,其返回的对象是Object属性,与构造函数无关


0 0
原创粉丝点击