Note that there are some explanatory texts on larger screens.

plurals
  1. POJavaScript's anonymous objects prototype
    primarykey
    data
    text
    <p>I learn JavaScript's "OOP" models, and looking forward to an advice how can I code around some problem I faced. (I will use the terminology "instance" later however now I know there's no instances in JavaScript.) Consider the following code:</p> <pre><code>function Class1(){ this.locvar1 = "locvar1"; this.locvar2 = "locvar2"; } function Class2(){ this.set = function(){ this.locvar1 = "ch_locvar1"; } } Class2.prototype = new Class1; //we'll get two instances from Class2 var x = new Class2(); x.set(); // we'll change the x's field with that (hoping that) var y = new Class2(); // hoping that this will be a totally new instance, // and the previous set() won't change it at all </code></pre> <p>Okay that code will work the way I wanted. I create two new objects, and their prototype will be the same still after I called x.set().</p> <pre><code>x.locvar1's value: "ch_locvar1" x.locvar2's value: "locvar2" y.locvar1's value: "locvar1" y.locvar2's value: "locvar2" their prototypes value: locvar1 : "locvar1", locvar2 : "locvar2" </code></pre> <p>The problem comes, when I try to use further objects in Class1's field.</p> <pre><code>function Class1(){ this.locvar1 = {a : "a"}; this.locvar2 = "locvar2"; } function Class2(){ this.set = function(){ this.locvar1.a = "ch_locvar1"; } } Class2.prototype = new Class1; var x = new Class2(); x.set(); var y = new Class2(); </code></pre> <p>That will out:</p> <pre><code>x.locvar1.a's value: "ch_locvar1" x.locvar2's value: "locvar2" what's ok, but..: y.locvar1.a's value: "ch_locvar1" y.locvar2's value: "locvar2" their prototypes value: locvar1.a : "ch_locvar1", locvar2 : "locvar2" </code></pre> <p>So it seems like with the statement "this.locvar1.a" I change the {a : "a"} object's prototype globally, and not a local instance of "this.locvar1"... </p> <p>Am I sure on this? How can I code around that? I tried to change "this.locvar1 = new {a : "a"};" because this seems logical to me, but the result is the same.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload