JS对象的几种创建方式

1、工厂模式创建对象

               function Parent(){
                   var o=new Object();
                   o.name="Qian";
                   o.age=21;
                   return o;                   
                }
                var x=Parent();
                alert(x.name);
                alert(x.age)

 

2、构造函数创建对象

            var demo=function(){ 
                return "脚本之家"; 
            }; 
            function Parent(){ 
                this.name="脚本"; 
                this.demo=demo; 
            }; 
                var x =new Parent(); 
                alert(x.name); 
                alert(x.demo()); 

 

3、原型模式

 (1).函数中不对属性进行定义
 (2).利用prototype属性对属性进行定义
 (3).同样的,不推荐使用这样方式创建对象

            var demo=function(){ 
                return "脚本之家"; 
            }; 
            function Parent(){ 

            }; 
            Parent.prototype.name="JavaScript"; 
            Parent.prototype.age="1"; 
            Parent.prototype.demo=demo; 
            var x =new Parent(); 
            alert(x.name); 
            alert(x.demo());

4、混合模式的构造函数

            function Parent(){ 
                this.name="脚本";  
            }; 
            Parent.prototype.demo=function(){ 
                return this.name; 
            };
                var x =new Parent(); 
                alert(x.demo());

 

5、动态原型方式

            function Parent(){ 
                this.name="脚本"; 
                if(typeof Parent._lev=="undefined"){ 
                    Parent.prototype.lev=function(){ 
                        return this.name; 
                    } 
                    Parent._lev=true; 
                } 
            }; 
            var x =new Parent(); 
            alert(x.lev());

 








posted @ 2018-03-07 22:16  fairy_21  阅读(84)  评论(0编辑  收藏  举报