Black
Black

Reputation: 20212

How to call method of a class inside of the class

I created a simple class myClass and added a method get_volume. How can i call get_volume inside of the class?

I always get Uncaught ReferenceError: get_volume is not defined

var test = new myClass();

function myClass()
{
    this.volume          = get_volume();
}

myClass.prototype.get_volume = function()
{
    return 100;
};

JSFIDDLE: https://jsfiddle.net/k01stzaq/

Upvotes: 2

Views: 73

Answers (4)

Pierfrancesco
Pierfrancesco

Reputation: 528

First declare the constructor and the prototype, than initialize your test object.

function myClass(spielname) 
{
    this.volume = this.get_volume();
}

myClass.prototype.get_volume = function() {
    return 100;
};


var test = new myClass();
console.log(test.volume); //should print 100

Hope this can help!

Upvotes: 1

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

You are calling get_volume as a global function, but it was defined as a method of myClass.
So get_volume method should be called in context of myClass object.
Change your code as shown below:

function myClass(spielname)
{
    this.volume = this.get_volume();
}

myClass.prototype.get_volume = function()
{
    return 100;
};

var test = new myClass();

Upvotes: 1

jeorfevre
jeorfevre

Reputation: 2316

1. define function internaly :

function myClass(spielname)      //Definition der Klasse "kicker"
{
    this.getVolume= function(){
      return this.volume;
    }
    this.volume          = 100;
}

or

2. add method to prototype :

 function myClass(spielname)      //Definition der Klasse "kicker"
    {

        this.volume          = 100;
    }
myClass.prototype.getVolume = function(){
  return this.volume;
}

Upvotes: 1

Pointy
Pointy

Reputation: 413682

The order of execution is what's causing your problem. You're calling new myClass() before the prototype is extended.

(Also, note that you're attempting to reference get_volume without this. I assume that was a typographical error, but perhaps not.)

Order the code as follows:

function myClass(spielname)      //Definition der Klasse "kicker"
{
    this.volume          = this.get_volume();
}

myClass.prototype.get_volume = function()
{
    return 100;
};

var test = new myClass();

The constructor itself was hoisted in your original, so the new myClass() call worked, but the assignment to test was before the extension of the prototype, so inside the constructor there's no get_value property until after that point (the protoytpe extension).

As a side note, it's common practice in JavaScript to use function names that begin with capital letters to indicate that a function is intended to be used as a constructor. It's not enforced by the language.

Upvotes: 4

Related Questions