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

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

posted @ 2020-10-15 17:50  浅笑·  阅读(124)  评论(0编辑  收藏  举报