Object.create(proto)返回(隐藏)构造函数的实例

Using the Object.create() method

Objects can also be created using the Object.create() method. This method can be very useful, because it allows you to choose the prototype object for the object you want to create, without having to define a constructor function.

o = {};

// Is equivalent to:

o = Object.create(Object.prototype);

o = Object.create(Object.prototype, {

  // foo is a regular data property

  foo: {

    writable: true,

    configurable: true,

    value: "hello",

  },

  // bar is an accessor property

  bar: {

    configurable: false,

    get() {

      return 10;

    },

    set(value) {

      console.log("Setting `o.bar` to", value);

    },

  },

});

// Create a new object whose prototype is a new, empty

// object and add a single property 'p', with value 42.

o = Object.create({}, { p: { value: 42 } });

With Object.create(), we can create an object with null as prototype. The equivalent syntax in object initializers would be the __proto__ key.

o = Object.create(null);

// Is equivalent to:

o = { __proto__: null };

By default properties are not writable, enumerable or configurable.

o.p = 24; // throws in strict mode

o.p; // 42

o.q = 12;

for (const prop in o) {

  console.log(prop);

}

// 'q'

delete o.p;

// false; throws in strict mode

To specify a property with the same attributes as in an initializer, explicitly specify writable, enumerable and configurable.

o2 = Object.create(

  {},

  {

    p: {

      value: 42,

      writable: true,

      enumerable: true,

      configurable: true,

    },

  },

);

// This is not equivalent to:

// o2 = Object.create({ p: 42 })

// which will create an object with prototype { p: 42 }


https://www.freecodecamp.org/news/a-beginners-guide-to-javascripts-prototype/

Object.create

Let's improve our example once again by using Object.create. Simply put, Object.create allows you to create an object which will delegate to another object on failed lookups. Put differently, Object.create allows you to create an object and whenever there's a failed property lookup on that object, it can consult another object to see if that other object has the property. That was a lot of words. Let's see some code.

const parent={name:'Stacey',age:35,heritage:'Irish'}

const child=Object.create(parent)

child.name='Ryan'

child.age=7

console.log(child.name)// Ryan

console.log(child.age)// 7

console.log(child.heritage)// Irish

So in the example above, because child was created with Object.create(parent), whenever there's a failed property lookup on child, JavaScript will delegate that lookup to the parent object. What that means is that even though child doesn't have a heritage property, parent does so when you log child.heritage you'll get the parent's heritage which was Irish.

Now with Object.create in our tool shed, how can we use it in order to simplify our Animal code from earlier? Well, instead of adding all the shared methods to the animal one by one like we're doing now, we can use Object.create to delegate to the animalMethods object instead. To sound really smart, let's call this one Functional Instantiation with Shared Methods and Object.create ?

Functional Instantiation with Shared Methods and Object.create

Functional Instantiation with Shared Methods and Object.create

? So now when we call leo.eat, JavaScript will look for the eat method on the leo object. That lookup will fail, then, because of Object.create, it'll delegate to the animalMethods object which is where it'll find eat.

So far, so good. There are still some improvements we can make though. It seems just a tad "hacky" to have to manage a separate object (animalMethods) in order to share methods across instances. That seems like a common feature that you'd want to be implemented into the language itself. Turns out it is and it's the whole reason you're here - prototype.

So what exactly is prototype in JavaScript? Well, simply put, every function in JavaScript has a prototype property that references an object. Anticlimactic, right? Test it out for yourself.

function doThing(){}

console.log(doThing.prototype)// {}

What if instead of creating a separate object to manage our methods (like we're doing with animalMethods), we just put each of those methods on the Animal function's prototype? Then all we would have to do is instead of using Object.create to delegate to animalMethods, we could use it to delegate to Animal.prototype. We'll call this pattern Prototypal Instantiation.

Prototypal Instantiation

Prototypal Instantiation

??? Hopefully you just had a big "aha" moment. Again, prototype is just a property that every function in JavaScript has and, as we saw above, it allows us to share methods across all instances of a function. All our functionality is still the same but now instead of having to manage a separate object for all the methods, we can just use another object that comes built into the Animal function itself, Animal.prototype.

At this point we know three things:

-How to create a constructor function.

-How to add methods to the constructor function's prototype.

-How to use Object.create to delegate failed lookups to the function's prototype.


Object.create(proto):创建一个新对象,这个对象继承(关联)了proto的属性,改变新对象的同名属性并不会影响原对象proto。如果直接用=来赋值,则只是一个对象的引用。

Object.create(protoObj):返回一个新对象,这个对象的构造函数的原型(prototype)指向protoObj。所以当访问新对象b.a的时候实际上是通过原型链访问protoObj.a。

Object.create(protoObj)生成了一个实例,这个实例的原型由protoObj来指定,但是它的构造函数F被隐藏了。

if(typeof Object.create!=="function"){

Object.create=function(proto, propertiesObject){

    function Constructor(){} //实现一个隐藏构造函数

    Constructor.prototype = proto //函数的原型设置为参数传进来的原型

    var o = new Constructor() // 返回一个构造函数的实例,此实例的__proto__指向参数proto

    Object.defineProperties(o, propertiesObject);

    return o;

}

or

return({__proto__:proto});

真正的Object.create()还可以传入第二个参数,这个参数与Object.defineProperties(,)的第二个参数格式相同, 通过第二个参数在新对象中重新创建一个属性,然后通过属性遮蔽原理避免修改原对象。


Object.create(null) 创建一个真正的空对象,并没有继承Object原型链上的方法。

// create an object with null as prototype

var o = Object.create(null);


var a = {} 并不是一个纯粹的空对象,它会继承原型链上的很多方法。

o={};

// is equivalent to:

o=Object.create(Object.prototype);


// Shape - superclass

function Shape(){

    this.x=0;

    this.y=0;

}

// superclass method

Shape.prototype.move=function(x, y){

    this.x+=x;

    this.y+=y;

    console.info('Shape moved.');

};

// Rectangle - subclass

function Rectangle(){

    Shape.call(this);// call super constructor.

}

Rectangle.prototype=Object.create(Shape.prototype); // subclass extends superclass

Rectangle.prototype.constructor=Rectangle; 

//If you don't set Rectangle.prototype.constructor to Rectangle, it will take the prototype.constructor of Shape (parent).To avoid that, we set the prototype.constructor to Rectangle (child).

var rect=new Rectangle();

console.log('Is rect an instance of Rectangle?',rect instanceof Rectangle);// true

console.log('Is rect an instance of Shape?',rect instanceof Shape);// true

rect.move(1,1);// Outputs, 'Shape moved.'

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,686评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,668评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,160评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,736评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,847评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,043评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,129评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,872评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,318评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,645评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,777评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,470评论 4 333
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,126评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,861评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,095评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,589评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,687评论 2 351