oop - How to obtain true de-referenced object instances in javascript -


i'm trying better understanding of object oriented patterns in javascript. particulary way emberjs implements classes .extend , .create parent class objects.

i've tried implement basic version of on own, no success, newly instantiated objects reference same object. i.e if increment private counter var in instance via public method, separately same instance b, b reflect both increments.

i able achieve de-referenced object via object.create(myclass), undesirable i'd achieve internally , not rely on client support native method.

here's jsbin of i've got: http://jsbin.com/zepaju/6/edit?js,console

thanks help!

this pretty big subject, because there isn't perfect way make javascript work java-- you'll have invent new coding idiom, , different people have different preferences.

looking @ linked code, it's hard sure you're gunning looks problem you're thinking of object's prototype "class", copied each "instance" (like in java)-- isn't case.

your create() function creating each "instance" doing object.create(poll), makes new object poll object prototype. when refer properties of resulting objects, , properties not directly defined on object, reference property of single poll object.

the fact you've sealed poll object's internal variables within closure doesn't make difference this; closure variables hidden outside world, accessible methods of poll object, , methods shared between "instances".

if want function spits out objects particular set of methods, , hide internal data in closure, might like:

function poll(challenger,incumbent) {   var challengervotes=0;   var incumbentvotes=0;   return {     voteforchallenger: function() {challengervotes++},     voteforincumbent: function() {incumbentvotes++},     winner: function() {return challengervotes>incumbentvotes ? challenger : incumbent}   } }  var poll1 = poll("edward","jacob"); var poll2 = poll("vanilla","stilton"); 

poll1 , poll2 not affect 1 another, , there no way access vote counts of either except through supplied methods. appreciate you're looking more generic approach example of how might start.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

jsf - How to ajax update an item in the footer of a PrimeFaces dataTable? -

django - CSRF verification failed. Request aborted. CSRF cookie not set -