JavaScript面向对象2

3.原型方式创建对象

    该方法利用对象的prototype属性,把他看成创建新对象所依赖的原型。然后所有的方法和属性都被直接赋予prototype属性。重新前面的Student类,;代码如下:

function Student(){
}
Student.prototype.name="zhangsan";
Student.prototype.age=25;
Student.prototype.sex="";
Student.prototype.showStudent=function(){
    alert("我叫"+this.Name+",今年"+this.Age+"岁,性别"+this.Sex);
};
var student1 = new Student();
var student2 = new Student();

4.混合的构造函数/原型方式

    利用构造函数定义对象的属性,利用原型方式定义对象函数。这种方式与其他语言创建对象一样。               

function Student(name,age,sex){
   
var student = new Object();
    studnet.Name = name ;
    student.Age = age;
    student.Sex = sex ;
}
Student.prototype.showStudent = function(){
    alert("我叫"+this.Name+",今年"+this.Age+"岁,性别"+this.Sex);
};
var student1 = createStudent("zhangsan",26,"");
var student2 = createStudent("lisi",25,"");
student1.showStudent();

5.动态原型方法              

function Student(name,age,sex){
   
var student = new Object();
    studnet.Name = name ;
    student.Age = age;
    student.Sex = sex ;
   
if(typeof Student._initialized == "undefined"){
        Student.prototype.showStudent = function(){
            alert("我叫"+this.Name+",今年"+this.Age+"岁,性别"+this.Sex);
        };
        Student._initialized = true;
    }
}
    直到检查typeof Student._initialized 是否等于undefined之前,这个构造函数都没发送变化。这行代码是动态原型中最重要的部分,如果这个值没有定义构造函数就会创建该方法,并给该方法赋值一次。
    总结,在JavaScript面向对象1和JavaScript面向对象2中,我们学习了大概5种javascript对象的创建形势,那我们应该使用哪一种呢?目前最广泛使用的是混合的构造函数/原型方式,动态原型方式也比较流行,最好不要单独使用经典的构造函数或原型方式。


 

 

 

posted on 2010-01-25 10:23  popzh2004  阅读(122)  评论(0)    收藏  举报

导航