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).

  • 相关阅读:
    react 踩坑第一天
    vue-cli+axios+跨域
    vuex 进阶 mapState mapGetter mapActions mapMutations
    vue Bus
    各种html布局
    echarts柱状图设置渐变色
    html设置一个当前时间
    css设置字体渐变色
    C++中指针与引用详解
    go-admin 开源后台管理系统
  • 原文地址:https://www.cnblogs.com/nullcnb/p/3653163.html
Copyright © 2011-2022 走看看