0

Was looking through best practices when dealing with external objects for example and ran across this article about why not to modify objects you do not own.

Reasoning is fairly sound, my question is how would I go about implementing this. For reference my code behaviour is current like this (custom object being owned by a 3rd party, Google maps):

var cObj = new customObject();
//I need to custom properties in addition to what Google provides
//So I insert new properties:
cObj.myProp1 = 1;

Article gives good reasons as to why its a bad practice therefore I do this:

function objWrapper(e){
   var cObj = e.cObj ? e.cObj : null;
   var myProp1 = e.myProp1 ? e.myProp1 : null;
}

//Here I create a copy of my wrapper and insert the Custom Object into it:
var obj - new objWrapper({});
var cObj = new customObject();

//Then I insert the cObj reference to the wrapper
obj.cObj = cObj;

This approach works fine when dealing with just variables but if say I ever need to access another child of the obj I would need to add in a circular reference like so:

cObj.obj = obj;

Which is not ideal, with a OO language I can see how to do this properly, not quite sure how to proceed in JS. I don't see how prototypes would really help here either.

PS: The actual code I'm working with is here but a more generalised explanation is what I'm looking for.

Cœur
  • 37,241
  • 25
  • 195
  • 267
boarnoah
  • 139
  • 2
  • 8
  • 1
    quick question: how to do it properly with an OO language? – Lim H. Feb 04 '16 at 01:37
  • @LimH. I was thinking along the lines of C#/Haxe where you would access the parent through super. etc... It appears JS has no such upwards relationship natively: http://stackoverflow.com/a/1789909/4433646 – boarnoah Feb 04 '16 at 01:57

1 Answers1

1

You don't need that new thing for the wrapper. for objects you can just use { }.

var obj = new customObject();

var wrapper = { 'childobj' : obj, 'anotherProperty': 1 };
console.log(wrapper.childobj);
Shai UI
  • 50,568
  • 73
  • 204
  • 309
  • How does accessing the wrapper's anotherProperty from a function from obj work. // later in the code: obj.addListener('click', function(){ //Here I would prefer having access to wrapper's other children/functions console.log(wrapper.anotherProperty); console.log(wrapper.anotherFunction()); }); In say C#, Haxe etc.. I would use a keyword base/super to access this parent. Or this that considered bad practice to begin with (I see it a lot with with Frameworks, Unity for example). Code here(SO comments are bad =( ): https://gist.github.com/boarnoah/df88d579d5f5ca8bc42b – boarnoah Feb 04 '16 at 01:46
  • obj.parent = wrapper; (after you've wrapped it).then console.log(obj.parent.anotherProperty); note however that if you have a circular reference like that, you won't be able to stringify it to json. – Shai UI Feb 04 '16 at 01:49