javascript - Object.create works new() doesn't -


having this:

sillyobject = {     init: function init(sillysettings) {         name = sillysettings.name     } };  sillyobject.showalert = function(x) {     return alert(x); }; 

when run code:

var sillyvar  = new sillyobject() sillyvar.init(mysettings); silly.showalert("silly!"); 

i error instead if run same thing using object.create runs..

var sillyvar  = object.create(sillyobject); sillyvar.init(mysettings); silly.showalert("silly!"); 

any (silly) appreciated.

new , object.create 2 fundamentally different things.

new going expect followed function, , if not (as saw) give error. because new expects call constructor function , use basis new execution context. during context, function has this bound scope of execution context. once function done executing returns this value has had data attached it. in example, this:

function sillyobject() {} sillyobject.prototype.init = function(sillysettings) {    //perhaps wanted attach name sillyobject?    name = sillysettings.name;    //which    this.name = sillysettings.name;    //because `this` here refers object context (remember?) }; sillyobject.prototype.showalert = function(x){    return alert(x);//returning alert returns undefined (not sure why used here) }; 

and use new, create execution context using constructor , attach prototype , end new instance of sillyobject (all instances different).

var = new sillyobject(); so.init(mysettings); so.showalert("silly!"); 

object.create() on other hand expecting object argument (which why version worked here). create new object using object argument template basically. or mdn explains it "the object.create() method creates new object specified prototype object , properties". creates copy if nothing else done object, , why alert worked here not in new version.


Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -