zoukankan      html  css  js  c++  java
  • js创建对象的几种方式

    一、new 操作符 + Object 创建对象

    var person = new Object();
    person.name = "lisi";
    person.age = 21;
    person.family = ["lida","lier","wangwu"];
    person.say = function(){
    alert(this.name);
    }
    

    二、字面式创建对象

    var person ={
      name: "lisi",
      age: 21,
      family: ["lida","lier","wangwu"],
      say: function(){
        alert(this.name);
      }
    };
    

    三、工厂模式

    function createPerson(name,age,family) {
        var o = new Object();
        o.name = name;
        o.age = age;
        o.family = family;
        o.say = function(){
            alert(this.name);
        }
        return o;
    }
    

    四、构造函数模式

    function Person(name,age,family) {
        this.name = name;
        this.age = age;
        this.family = family;
        this.say = function(){
            alert(this.name);
        }
    }
    

    五、原型模式

    function Person() {
    }
    Person.prototype.name = "lisi";
    Person.prototype.age = 21;
    Person.prototype.family = ["lida","lier","wangwu"];
    Person.prototype.say = function(){
        alert(this.name);
    };
    var person1 = new Person();        //创建一个实例person1
    console.log(person1.name);        //lisi
    

    六、混合模式(构造函数模式+原型模式)

  • 相关阅读:
    xxx
    部署在自己的加了分享,试下
    疑问
    去掉分享
    womenzijide_jiafenxiang
    womenzijide2
    womenzijide
    xiugai-去除js注释
    xiugai2
    《设计模式之禅》读书笔记(一)——单例模式
  • 原文地址:https://www.cnblogs.com/loveliang/p/13671285.html
Copyright © 2011-2022 走看看