zoukankan      html  css  js  c++  java
  • 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版)》

  • 相关阅读:
    java
    EL表达式详解
    SVN的安装与配置
    javascript高级程序设计学习笔记
    java基础知识
    javascript高级程序设计学习笔记Chapter 5: Reference Types
    javascript模态,非模态窗体
    javascript执行顺序
    javascript的执行顺序2
    自动补全+汉字拼音双查(1)数据库
  • 原文地址:https://www.cnblogs.com/planetwithpig/p/11530794.html
Copyright © 2011-2022 走看看