zoukankan      html  css  js  c++  java
  • javascript中对象的创建构造函数模式

    function Person(name,age,job){
        this.name=name;
        this.age=age;
        this.job=job;
        this.sayName=function(){
            alert(this.name);
        };
    }    
    var person1=new Person("null",25,"Software Engineer");
    var person2=new Person("null2",250,"Software Engineer");

    与工厂模式区别:

    1.没有显式创建对象

    2.直接将属性和方法赋给了作用域

    3.没有return语句

    构造函数模式的创建步骤:

    1.创建一个新对象

    2.将构造函数的作用域赋值给新对象(因此this就指向了这个新对象)

    3.执行构造函数中的代码(为这个新对象添加属性)

    4.返回新对象

    alert(person1.constructor==Person);//true
    alert(person2.constructor==Person);//true
    
    alert(person1 instanceof Object);//true
    alert(person1 instanceof Person);//true
    alert(person2 instanceof Object);//true
    alert(person2 instanceof Person);//true

      创建自定义的构造函数意味着将来可以将它的实例标识为一种特定的类型,这里是Person,这正是构造函数模式胜过工厂模式的地方,当然,它们同时Object的实例(所有对象均继承自Object).

  • 相关阅读:
    7、python数据类型之集合set
    python基本数据类型练习
    matplotlib
    numpy常用函数
    pillow包
    keras-tensorflow版本对应
    python-激活和切换运行环境
    端口监控
    numpy
    低风险创业笔记
  • 原文地址:https://www.cnblogs.com/nullcnb/p/3653163.html
Copyright © 2011-2022 走看看