码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2019-09-17 00:08:07      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:==   rip   color   student   使用   tor   组合   htm   mda   

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

<!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版)》

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

标签:==   rip   color   student   使用   tor   组合   htm   mda   

原文地址:https://www.cnblogs.com/planetwithpig/p/11530867.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!