JS面向对象——组合使用构造函数模型与原型模型

该模型为创建自定义类型最常用的方式。

<!DOCTYPE html>
<html>
<head>
    <title>组合使用构造函数模型和原型模型</title>
    <script type="text/javascript">
        //组合使用构造函数模型和原型模型——构造函数模型用于定义实例属性,原型模型用于定义方法和共享属性。    
        function Student(name,age,sex){            
            this.name=name;
            this.age=age;
            this.sex=sex;
            this.friends=["Kitty","Court"];            
        }        
        Student.prototype={
            constructor:Student,
            sayName:function(){
                alert(this.name);
            }
        }

        var stu1=new Student("Lucy",10,"girl");
        var stu2=new Student("Bob",9,"boy");
        stu1.friends.push("Van");
        alert(stu1.friends);//"Kitty,Court,Van"
        alert(stu2.friends);//"Kitty,Court"
        alert(stu1.friends===stu2.friends);//false
        alert(stu1.sayName===stu2.sayName);//true
    </script>
</head>
<body>
</body>
</html>

部分摘自《JavaScript高级程序设计(第3版)》

posted @ 2019-09-16 23:04  用脑袋行走的人  阅读(335)  评论(0编辑  收藏  举报