1

There are no actual classes in javascript. But you have to work with what you get.

Lets take this example "Class":

var example = function (string) {
  this._self = string;
}

With the above, you could do something like:

var ex = new example("Hello People."),
    display = ex._self; // returns "Hello People."

I thought that by using something like example.prototype.newFun = function(){} would add a new property to that "Class". But it isn't working in my code.

Here is the full code i'm testing:

var example = function (string) {
  this._self = string;//public, var like, storage
}

var showExample = new example("Hello People");
showExample.prototype.display = function (a) {//code stops here, with error "Uncaught TypeError: Cannot set property 'display' of undefined"
  return a;
}
console.log(showExample._self);
console.log(showExample.display("Bye"));

What i'm trying to do is add the display function to the example function as a "public function". I might be doing something wrong.

Shawn31313
  • 5,978
  • 4
  • 38
  • 80

5 Answers5

5

It's not the object that has the prototype, it's the function that you use to create the object:

var example = function (string) {
  this._self = string;
}

example.prototype.display = function (a) {
  return a;
};
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
3

Because there's no prototype for showExample - it's only an instance of example. Try to do this: example.prototype.display = function (a) {} and it will work.

Here's a bit more on classes in JavaScript:

Community
  • 1
  • 1
CamelCamelCamel
  • 5,200
  • 8
  • 61
  • 93
3

You try to add a method to the prototype of the instance of example (showExample). The instance has no prototype. Try example.prototype.display = function() {/*...*/}; (in other words, add the method to the prototype of the constructor of showExample, that is example) and check again. After that, all instances of example 'know' the display method, or in your words, display is 'public' to all instances.

You can add the method to the instance using showExample.display = function() {/*...*/};. Using that, only showExample knows the the display method.

KooiInc
  • 119,216
  • 31
  • 141
  • 177
3

You can modify to the constructor of showExample ..

ex.

showExample.constructor.prototype.display = function (a) {
  return a;
}
alaasdk
  • 1,988
  • 19
  • 21
1

in your case showExample is an object of example...

use

example.prototype.display = function(a)...
user934801
  • 1,119
  • 1
  • 12
  • 30