zoukankan      html  css  js  c++  java
  • JavaScript创建对象的七种方法

    一、 工厂模式

    创建:

    function createPerson(name,behavior){
    var p=new Object();
    p.name=name;
    p.behavior=behavior;
    p.getInfo=function(){
    alert(this.name+"在"+this.behavior)
    }    
    p.getInfo();
    }
    var person=createPerson("张三",["打游戏","看书"]);

    二、 构造函数模式

    创建:

    function createPerson(name,behavior){
    this.name=name;
    this.behavior=behavior;
    this.getInfo=function(){
    alert(this.name+"在"+this.behavior)
    }
    }
    var person=new createPerson("张三",["打游戏","看书"]);
    person.getInfo();


    三、原型模式

    创建:

    function createPerson(){}
    createPerson.prototype.name="张三";
    createPerson.prototype.behavior=["打游戏","看书"];
    createPerson.prototype.getInfo=function(){
    alert(this.name+"在"+this.behavior)
    }
    var person=new createPerson();
    person.getInfo();

    四、组合模式(构造函数与原型)

    创建:

    function createPerson(name,behavior){
    this.name=name;
    this.behavior=behavior;
    }
    createPerson.prototype.getInfo=function(){
    alert(this.name+"在"+this.behavior)
    }
    var person=new createPerson("张三",["打游戏","看书"]);
    person.getInfo();

    五、动态原型模式

    创建:

    function createPerson(name,behavior){
    this.name=name;
    this.behavior=behavior;
    if(typeof this.getInfo!="function"){
    createPerson.prototype.getInfo=function(){
    alert(this.name+"在"+this.behavior);
    }    
    }
    }
    var person=new createPerson("张三",["打游戏","看书"]);
    person.getInfo();

    六、寄生构造函数模式

    创建:

    function createPerson(name,behavior){
    var p={};
    p.name=name;
    p.behavior=behavior;
    p.getInfo=function(){
    alert(this.name+"在"+this.behavior)
    }    
    p.getInfo(); 
    }
    var person=new createPerson("张三",["打游戏","看书"]);

    七、稳妥构造函数模式

    创建:

    function createPerson(name,behavior){
    var p={};
    p.getInfo=function(){
    alert(name+"在"+behavior)
    }    
    p.getInfo(); 
    }
    
    var person=new createPerson("张三",["打游戏","看书"]);
    
     

    参考网址:http://www.cnblogs.com/ifat3/p/7429064.html

  • 相关阅读:
    leetcode 175 Combine Two Tables join用法
    spark学习及环境配置
    html表格设计
    免费的论文查重网站
    php利用msqli访问数据库并实现分页,
    php利用href进行页面传值的正确姿势
    php+mysql时报错:Unknown column '' in 'field list'解决方案
    使用XMLHttpRequest解析json
    用自定义的函数将gps转换为高德坐标
    WeakHashMap回收时机
  • 原文地址:https://www.cnblogs.com/jian138/p/8531152.html
Copyright © 2011-2022 走看看