创建对象

创建对象

new Object()

var d = new Object();

Object.create()

var a = Object.create(null);

内部原理

Object.create = function (proto, propertiesObject) {
    if (typeof proto !== 'object' && typeof proto !== 'function') {
        throw new TypeError('Object prototype may only be an Object: ' + proto);
    } else if (proto === null) {
        throw new Error("This browser's implementation of Object.create is a shim and doesn't support 'null' as the first argument.");
    }

    if (typeof propertiesObject != 'undefined') {
        throw new Error("This browser's implementation of Object.create is a shim and doesn't support a second argument.");
    }

    function F() {}
    F.prototype = proto;

    return new F();
};

{}

var b = {};

Object.create(null) vs {}

默认情况下,JavaScript 的对象继承自 Object,所以 {}.constructor.prototype == Object.prototype。但是如果你主动指定了 null 作为 prototypeObject.create(null)),那么这个对象不会继承任何属性,也就是没有 __proto__ 这个属性。

{}Object.create(Object.prototype) 是等价的。

function 构造器

var Obj = function(name) {
  this.name = name
}
var c = new Obj("hello"); 

function 构造器 + prototype

function myObj(){};
myObj.prototype.name = "hello";
var k = new myObj();

ES6 class

class myObject  {
  constructor(name) {
    this.name = name;
  }
}
var e = new myObject("hello");

单例

var l = new function(){
  this.name = "hello";
}

参考