Javascript MVC: model method called inside controller returns udefined -> but why?

Viewed 36

I have been learning javascript and I tried to use MVC. I noticed a problem and I could not find the answer to why, anywhere. The problem is following:

I have a class Model as follows in model.js:

export default class Model {
    constructor() {}

    speak(word) {
        return word;
    }
}

and controller (controller.js):

import Model from './model.js';

export default class Controller {
    constructor() {
        this.model = new Model();
    }

    speak(word) {
        this.model.speak(word);
    }
}

I am only explicitly writing export and import here, since I have it this way in my app and I want this example code to mimic my problem as much as possible. I have separate files for each class or component. Anyway, later, in my main AppController, I have

import Controller from './controller.js';

const controller = new Controller();
console.log(controller.speak('Hi'));

The last line always returns undefined, no matter what I return, whether it is, as in this case, a simple string, or any attribute of model class. I know, when I do this:

controller.model.speak('Hi');

Then everything is OK. My question therefore is not how to solve it, but why is that happening? Thank you very much for your answers.

3 Answers

You need to make Controller.speak return a value.

speak(word) {
    return this.model.speak(word);
}

You have not returned a result from the controller speak() function.

controller.model.speak('Hi') instead of this if you write console.log(controller.model.speak('Hi')); you will see that Hi.

Related