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

    一、字面量方式

    var obj = {
        name: 'mm',
        age: 18,
        sayName: function() {
            console.log(this.name);
        }
    }
    

    问题:创建多个对象时会造成代码冗余,很占内存空间。

    二、工厂模式

    function createToy(name) {
        var o = new Object();
        o.name = name;
        o.say = function() {
            console.log(this.name);
        }
        return o;
    }
    var toy1 = createToy('car');
    toy1.say();
    var toy2 = createToy('taxi');
    toy2.say();
    var toy3 = createToy('bus');
    toy3.say();
    console.log(toy1 instanceof Object);
    console.log(toy2 instanceof Object);
    console.log(toy3 instanceof Object);
    

    问题:虽然解决了对象字面量创造对象冗余的问题,但是存在对象识别的问题

    三、构造函数模式

    function Toy(name) {
        this.name = name;
        this.say = function() {
            console.log(this.name);
        }
    }
    var toy1 = new Toy('car');
    var toy2 = new Toy('car');
    console.log(toy1.constructor);
    console.log(toy2.constructor);
    console.log(toy1.say === toy2.say); // false
    

    问题:解决了工厂模式的问题,但是相同方法重复创建就浪费了内存空间。

    四、原型模式

    function Person() {};
    Person.prototype = {
        constructor: Person,
        name: 'mm',
        friends: ['mike','helen'],
        say: function() {
            console.log(this.name);
        }
    }
    var toy1 = new Person('train');
    var toy2 = new Person('bus');
    toy1.friends.push('suhai');
    console.log(toy1.friends);
    console.log(toy2.friends);
    

    问题:共享方法,解决了构造函数的问题。但是当前实例的引用类型的属性被所有实例共享

    电脑刺绣绣花厂 http://www.szhdn.com 广州品牌设计公司https://www.houdianzi.com

    五、组合模式(构造函数+原型模式)

    function Person(name) {
        this.name = name;
        this.friends = ['mike','helen'];
    };
    Person.prototype = {
        constructor: Person,
        say: function() {
            console.log(this.name);
        }
    }
    var toy1 = new Person('train');
    var toy2 = new Person('bus');
    toy1.friends.push('suhai');
    console.log(toy1.friends);
    console.log(toy2.friends);
    

    这是常用的创建方式。
    通过构造函数模式定义实例属性,通过原型模式定义方法和共享的属性。

  • 相关阅读:
    Restful levels &HATEOAS基本介绍~
    跨源资源共享(CORS)概念、实现(用Spring)、起源介绍
    Ubuntu下math库函数编译时未定义问题的解决
    常用软件清单~
    JetBrains PyCharm 专业版激活
    hello1.java内容简单介绍
    hello1 web项目中web.xml作用分析
    hello2 source analisis(notes)
    Servlet filter
    分析helo1项目中的 Web.xml
  • 原文地址:https://www.cnblogs.com/qianxiaox/p/13821985.html
Copyright © 2011-2022 走看看