JavaScript如何建立一个对象?

1.对象字面量

最经常运用的最轻易的建立要领,以下所示

var foo = {
    bar: 'bar'
}

实在字面量是运用object.create的快捷方式,下面代码与上面等价

var foo = Object.create(Object.prototype,{
    bar: {
        writable: true,
        configurable: ture,
        value: 'bar'
    }
})

2.new Object()

var Person = function(myname){
    this.name = myname;
}
var me = new Person('Joe');

当我们议论到new Object(),实际上我们在议论new运算符,new运算符实际上做了一下事情

2.1建立一个新对象

me = {}

2.2将新建立的对象的组织函数链接到函数Person上

//true
me.constructor === Person

2.3将对象的原型链链接到Person.prototype

使新建对象能够沿原型链运用组织函数的要领

//true
me.__proto__ === Person.prototype

2.4将传入的参数富足给新建立的对象

3.Object.create(ES5)

在ES5之前,只能运用new来完成原型链集成。总而言之Object.create()和字面量对象应当替代new object()要领。
Object.create()能够吸收两个参数:供应原型的对象,可选属性对象(这个对象包括对新建立对象的设置)。

var Car = {
    drive: function (miles) {
        return this.odometer += miles;
    }
};
var tesla = Object.create(Car, {
    'odometer': {
        value: 0,
        enumerable: true
     }     
));

//输出10
console.log(tesla.drive(10));
    原文作者:ssshooter
    原文地址: https://segmentfault.com/a/1190000009642708
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞