JS面向对象——构造函数模型

时间:2019-09-16
本文章向大家介绍JS面向对象——构造函数模型,主要包括JS面向对象——构造函数模型使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

ECMAScript中的构造函数可用来创建特定类型的对象。我们可以创建自定义构造函数,从而定义对象类型的属性和方法,解决工厂模型中对象识别的问题。

<!DOCTYPE html>
<html>
<head>
    <title>构造函数模型</title>
    <script type="text/javascript">
        function Student(name,age,sex){//构造函数首字母大写,普通函数首字母小写
            //直接将属性和方法赋值给this对象
            this.name=name;
            this.age=age;
            this.sex=sex;
            this.sayName=function(){
                alert(this.name);
            };
        }

        /****************************** 构造函数模型 ******************************/
        /*创建Student的新实例实际经历的步骤:
            (1)创建一个新对象
            (2)将构造函数的作用域赋值给新对象(因此this指向了新对象)
            (3)执行构造函数中的代码(为新对象添加属性和方法)
            (4)返回新对象
        */
        var stu1=new Student("Lucy",10,"girl");//使用操作符new
        var stu2=new Student("Bob",9,"boy");

        //以上的stu1和stu2这两个对象的constructor(构造函数)属性均指向Student
        alert(stu1.constructor==Student);//true
        alert(stu2.constructor==Student);//true

        //对象的constructor属性最初是用来表示对象类型的。检测对象类型使用instanceof更可靠
        alert(stu1 instanceof Student);//true
        alert(stu2 instanceof Student);//true
        alert(stu1 instanceof Object);//true
        alert(stu2 instanceof Object);//true
        /*************************************************************************/

        /**************************** 1.构造函数当作函数 **************************/
        //当作构造函数
        var stu3=new Student("Nike",10,"boy");
        stu3.sayName();//"Nike"
        //当作普通函数
        Student("Greg",13,"boy");//添加到window对象
        window.sayName();//"Greg"
        //在另一个作用域中调用
        var o=new Object();
        Student.call(o,"Kristen",8,"girl");
        o.sayName();//"Kristen"
        /************************************************************************/

        /**************************** 2.构造函数模型问题 *************************/
        //问题:每个方法都要在每个实例上重新创建一遍,不同实例上的同名函数是不相等的。为解决这一问题于是就有了原型模型
        alert(stu1.sayName==stu2.sayName);//false
        /************************************************************************/
       
    </script>
</head>
<body>
</body>
</html>

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

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