Note that there are some explanatory texts on larger screens.

plurals
  1. POWorking with JavaScript prototypes and accessing base class fields.
    primarykey
    data
    text
    <p>I am new to pseudo classes and prototypes in JavaScript and I am having a bit of difficulty implementing it properly. What I am trying to do is have a base 'class' with some fields then create a prototype of that base class with my methods defined as object literals. I am torn between doing it this way and just using singletons inside my base class for my methods. I think though that doing it this way is a little more elegant and I think I am actually not creating every method every time I create a new object. </p> <p>Anyways, the small issue I am having is referencing the fields of my base class in my methods. Because when I try to reference them as this.field this is referring to the current function/ scope but I want it to reference the newly create object. Is there a work around for this or should I change the way I am creating my methods. </p> <p>Below is some code that I think will make it more clear what I am doing and the problem I am having.</p> <pre><code>function BaseClass() { this.items[]; this.fieldOne = "asdasd"; } BaseClass.prototype = { methodOne: function (input) { function addElement(a. b) { var element = {}; element.prop1 = a; element.prop2 = b; //The issue I am having is that items is undefined, how can I refernce the parent class object. this.items.push(element); } function traverse() { //go through a list and add a bunch of elements addElement("ASdasd", 324); } }, methodTwo: function () { //see now fieldOne is asdasd console.log("fieldOne" + fieldOne); } } var forTest = new BaseClass(); forTest.methodTwo(); </code></pre> <p>So yeah I want to have some fields in the parent class that I can access from any method, but I would rather not just put the functions in my base class so that I do not create every method everytime I create a new object from BaseClass. Is there a work around or a better way to implement this? </p> <p>Thanks in advance for the help. </p>
    singulars
    1. This table or related slice is empty.
    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.
    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