planetwithpig

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

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

分类:

技术点:

相关文章:

  • 2021-10-21
  • 2018-04-08
  • 2021-09-03
  • 2021-04-27
  • 2021-06-11
  • 2022-01-14
  • 2021-11-16
  • 2021-11-29
猜你喜欢
  • 2022-01-01
  • 2021-06-10
  • 2018-02-04
  • 2018-04-18
  • 2021-04-29
  • 2021-10-23
  • 2021-10-17
相关资源
相似解决方案