javascript---面向对象:构造函数

首先javascript是基于对象的,即对象无处不在。

本节我们来讲讲js的构造函数。

创建对象实例有两种方法:第一种是工厂模式,第二种是构造函数

 

1.工厂模式

 1     function CreateObject(name,age){
 2             var obj=new Object();
 3             obj.name=name;
 4             obj.age=age;
 5             obj.run=function(){
 6             return this.name+this.age+'运行中······';
 7             }
 8         return obj;
 9         }
10         var box1=CreateObject('Lee',100);
11         var box2=CreateObject('kkk',200);
12         alert(box1.run());
13         alert(box2.run());  


2.构造函数

    function Box(name,age){
        this.name=name;        
        this.age=age;
        this.run=function(){
        return this.name+this.age+'运行中······';
        }
    }
    function Desk(name,age){
        this.name=name;
        this.age=age;
        this.run=function(){
            return this.name+this.age+'运行中······';
        }
    }
    var box1=new Box('Lee',100);            //实例化对象
    var box2=new Box('kkk',200);
    var box3=new Desk('jack',300);
    alert(box1.run());
    alert(box2.run());
    alert(box3.run());
    alert(box1 instanceof Box);                //解决了对象识别问题
    alert(box3 instanceof Desk);


解答:构造函数相比工厂模式,解决了对象识别的问题,即可以区别开实例化的对象。

 


构造函数中涉及了一些问题:

补充:

 

• 内存:函数是引用类型的,其地址是固定的,存放在栈中,栈里的内存分配是固定的,所以基本类型的值都存放在栈中;而地址对应的值则存放在堆中,堆内的内存分配不固定。

• 调用:当调用函数时,由于函数是引用类型,首先先在栈中找到其地址,然后再在堆中找到相应的值;而基本类型则是直接在栈中寻找并返回。

 1     function Box(name,age){
 2         this.name=name;        
 3         this.age=age;
 4         this.run=function(){
 5             return this.name+this.age+'运行中······';
 6         }
 7     }
 8     function Desk(name,age){
 9         this.name=name;
10         this.age=age;
11         this.run=function(){
12             return this.name+this.age+'运行中······';
13         }
14     }
15     var box1=new Box('Lee',100);            //实例化对象
16     var box2=new Box('Lee',100);
17     alert(box1.age==box2.age);            //基本类型相等
18     alert(box1.age===box2.age);
19     alert(box1.run()==box2.run());            //函数的值相等
20     alert(box1.run==box2.run());            //函数的地址不同,引用类型

 

构造函数中的函数run在不断实例化时产生冗余,即不断的在内存中开辟新的空间,而函数的内容是相同的,对内存不利。

解决方案:

可以使他们的引用地址一样,在全局加同一个函数,使指向的地址一样,不过此方法不好,可以直接调用,有副作用

    function run(){
    return this.name+this.age+'运行中······';
    }
    function Box(name,age){
        this.name=name;        
        this.age=age;
        this.run=run;
        }
        function Desk(name,age){
            this.name=name;
            this.age=age;
            this.run=run;
} var box1=new Box('Lee',100); //实例化对象 var box2=new Box('Lee',100); alert(box1.run()==box2.run()); //函数的值相等 alert(box1.run==box2.run); //true

 

posted @ 2016-03-20 00:04  GacentJohn  阅读(167)  评论(0编辑  收藏  举报