0

So I'm trying to write an app in javascript and I'm trying to lear OOP javascript. So I created like a simple "class" and in the prototype I'm setting an array to be empty. When I create an object it passes two values to this array, but when I create another object it retains the values from the previous object I created..

I have a jsfiddle showing my problem..

http://jsfiddle.net/UGWt8/3/

Please let me know why is that happening..

I thought when I created a new object like:

var data = new the_namespace.Test();

it'll be clean without any data..

(This could be something very simple, but again I'm still kind of new to javascript..) Thanks

1 Answers1

2

Objects on the prototype are shared across instances; move the definition of array to the constructor: http://jsfiddle.net/UGWt8/4/

circusbred
  • 1,240
  • 8
  • 8
  • Got it.. so in the prototype I'll define generic functions that'll be shared with the instances but variables with specific values for an specific instance should be outside the prototype ? – vicgonzalez25 Apr 07 '14 at 18:48
  • This behavior depends on the type of value assigned to the member; this will not happen for primitives (String, Number, Boolean), but Array and Objects. To avoid this type of error, it is usually best to use the pattern you've described. – circusbred Apr 07 '14 at 18:57
  • Sounds Good :) Thank so much for your help, I would give you a vote up but i'm new and cant :/ – vicgonzalez25 Apr 07 '14 at 19:10
  • @vicgonzalez25 assigning a value to an instance member (like ben.name in: var ben = new Person();ben.name=...) will cause the `name` member to be created on the instance no matter if the `name` member is somewhere in ben's prototype. Mutating members is a different story. It's explained here: http://stackoverflow.com/a/16063711/1641941 – HMR Apr 08 '14 at 02:04
  • @circusbred assigning object prototype members will cause the member to be shadowed as well, the difference is assignment versus mutating. Since string and number are immutable (can't be mutated) you can only change them trough assignment thus shadowing the member. See link in previous comment. – HMR Apr 08 '14 at 02:06