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

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

  • 相关阅读:
    Windows Phone 7 立体旋转动画的实现
    jQuery 表格Table插件汇总
    SNS社交类网站照片头像裁剪源码
    VS无法启动调试
    SQL Server中获取第一天、最后一天
    jQuery技巧总结
    IT人士应当知道的10个行业小内幕
    巧用SQL server临时表
    将Html文档整理为规范XML文档
    16个Javascript的Web UI库、框架及工具包
  • 原文地址:https://www.cnblogs.com/qianxiaox/p/13821985.html
Copyright © 2011-2022 走看看