javascript - Explain Object.create(), new -
i know type of question has been asked , answered million times, still don't understand this.
everything in javascript object. there exists prototype chain javascript runtime searches methods , properties. these 2 things clear. (think i) understand new statement does. maybe problem don't understand object.create
does. have been using following javascript design pattern:
superclass = function(){ this.superprop = 'some super property'; }; subclass = function(){ this.subprop = 'some (not so) super property'; }; superclass.prototype.somesupermethod = function(){console.log("i'm super.")}; subclass.prototype = object.create(superclass.prototype); subclass.prototype.constructor = subclass; var instance = new subclass(); instance.somesupermethod(); // great! that's super!
but, have know clue why can't write:
subclass = object.create(superclass);
subclass = superclass;
subclass = new superclass;
subclass.prototype = superclass.prototype;
subclass = new superclass();
subclass.prototype = superclass;
(or of combinations above). in short, guess don't know .prototype property of function or why need object.create prototype if want subclass
inherit supclass
.
i don't understand superclass.prototype.constructor
means. how object different superclass
?
i don't understand why need write new subclass()
, not new subclass
. what's difference?
alright, i'm op question. but, i'm going try form comprehensive answer question (as comprehensive answer satisfies me).
first things first: in javascript object. object? object is thing methods , properties associated it. might ask: "okay, string object? number 5 object?". that's interesting question. strictly, no. these fundamental javascript language called primitives. there 6 primitives in javascript: strings, numbers, boolean, null, undefined , symbol (symbols new of ecmascript 6, latest standard on javascript based - published officially: june 17, 2015).
the main components of objects primitives. can have functions return strings or add numbers. generic object container strings or numbers:
var mygenericobject = {var1: "string 1", var2: 42, var3: function(){ console.log("do something.") } };
all objects in javascript children of object class, functions. don't confused: while function class fundamental object, functions still descend object class, guess makes object class fundamental object in javascript (this why it's called object). however, object class descends null primitive (don't worry; that's ends). concept i'm sideways-addressing right called prototypical inheritance , core distinguishing feature of javascript.
but, javascript pretty smart. when try access methods exist objects thus, var teststring = "hello"
object
first, new
operator according ecmascript 5
(more in bit. i'm saving progress, temporarily).
Comments
Post a Comment