0

I am not familiar with oops implementation in js specific code.
I saw this code

var RandomNumberGameViewModel = function () {
            var self = this;

            Level = function (id, identifier) {
                return {
                    id: ko.observable(id),
                    identifier: ko.observable(identifier)
                };
            }

            self.GenerateRandomNumber = function () {
                var number = '';
                for (var i = 0; i < self.digitsLimit() ; i++) {
                    var randomNumber = Math.floor((Math.random() * self.digitsLimit()) + 1);
                    number += randomNumber;
                }
                return number;
            }
        }
  1. What will be called RandomNumberGameViewModel() is it a name of any function?
  2. I guess Level() is a function name then what is GenerateRandomNumber()? If both are functions then why is one pre-fixed with self keyword and the other is not?

Please explain the code which I highlighted here.

Thanks

GôTô
  • 7,974
  • 3
  • 32
  • 43
Thomas
  • 33,544
  • 126
  • 357
  • 626
  • 2
    tbh that's not a very good example of a knockout view model. If you want to learn how this code works look at knockouts interactive tutorials. http://learn.knockoutjs.com/ – David Barker Jul 18 '14 at 07:30
  • i am not after knockout rather i am after coding pattern. i like to know why one method is prefix with self and another is not prefix with self. – Thomas Jul 18 '14 at 08:19

1 Answers1

0

Technically, Level should be preceded by either var or self.. I don't know what the author intended, but there are two possibilities, as I see it:

  1. Level is supposed to be a private function inside RandomNumberGameViewModel, and therefore should read var Level = ....

  2. Level is supposed to be a public function on the RandomNumberGameViewModel "class", and should therefore read self.Level = ....

As is discussed here, you should never omit var for variables: What is the purpose of the var keyword and when to use it (or omit it)?

If you are interested in learning more about OOP in JavaScript (and other useful patterns), you should read http://addyosmani.com/resources/essentialjsdesignpatterns/book/ which I think explains things pretty well.

Community
  • 1
  • 1
Christoffer
  • 2,125
  • 15
  • 21
  • so u mean to say Level is private function that is why it is not prefix with self.Level. am i understood properly? – Thomas Jul 18 '14 at 09:17