「JavaScript」タグアーカイブ

javascript

【JavaScript】「Object.assign vs Object.create」のおもしろい議論みつけた

classをES5記述で継承する際に、createとassignの使い所について調べていたらみつけた。その概要
このコード

https://stackoverflow.com/questions/33692912/using-object-assign-and-object-create-for-inheritance

classをES5記述で継承する際に、createとassignの使い所について調べていたらみつけた。その概要

https://stackoverflow.com/questions/33692912/using-object-assign-and-object-create-for-inheritance

【JavaScript】Object.crateとassignを使ってnewしないでインスタンスを作る「FactoryFunction」

大変興味深い記事見つけました

ざっくり何をいっているかというと
「あなたがprototypeを理解していないならJavaScriptを理解していない」
衝撃的。。
classの継承はprototypeの継承と同じことですか??スタイルの違いですか??
No
classは青写真、設計図、subクラスとの関係。
いいかえるならclassがないとインスタンスは作れない
インスタンスメソッドはそれ自体class定義されていないと実行できない
まずインスタンスを作ってインスタンス上でメソッドを実行しなくてはならない。

prototype継承は
他のインスタンスから継承しているインスタンス。
prototype委譲して使っている。
インスタンスのprototypeを設定するとオブジェクトへの参照をもつ
オブジェクトは他のオブジェクトへのリンクをもつようになる。(concatenative inheritance 連接継承)

A class is a blueprint.
A prototype is an object instance.

Aren’t classes the right way to create objects in JavaScript?
クラスがオブジェクトを作る正しい方法なの??
No

let animal = {
animalType : "brown",
discribe (){
console.log("fafa")
}
}
これにprototpeに委譲させるObject.createを使って。

let animal = {
animalType : "brown",
discribe (){
console.log("fafa")
}
}
let mouse = Object.assign(Object.create(animal), {animalType: 'mouse'});
mouse.discribe()
//fafa
//mouseに別オブジェクト内のdiscribeメソッドがprototype委譲されている
//animalは「delegate prototype」となる

mose.animalType
//mouse
//自身のpropertyとして持っているのでprototypeチェーンを辿らない
JS Bin on jsbin.com

Object.createは
このまえやりました。
「we could attach delegate prototypes without using constructors and the `new` keyword」
この場合animalをnewとconstructorなしに、prototype委譲できる

「Don’t you need a constructor function to specify object instantiation behavior and handle object initialization?」
細かい初期設定や振る舞いを書くコンストラクターは必要ないってこと??

No

「Any function can create and return objects. When it’s not a constructor function, it’s called a factory function.」
どんな関数も作成、オブジェクトを返せる。それがコンストラクタではないとき、ファクトリー関数といわれる
JS Bin on jsbin.com

記事では
・privacy propertyのもち方
・new keywordが何をしているか
・instance of は嘘つきだ
・newはきもい!
・newを使うときとcreateではパフォーマンスに違いはあるのか
なども解説されています。
面白いし、英語記事から学ぶと英語とコードの勉強になって一石二鳥ですね。

でわまたーーー