0

Not sure why this construction of a class is not working, maybe I'm just calling the function in the wrong way? Here is my code:

  function zeros(bits, pattern) {
    this.bits = bits;
    this.pattern = pattern;
  };

  zeros.prototype.short = function() {
    return this.bits.match(this.pattern)[0].length;
  };

  heyJude = zeros('1100110011001100000011000000111111001100111111001111110000000000000011001111110011111100111111000000110011001111110000001111110011001100000011', /([0]).*?\1+/);
  console.log(heyJude.short());
bpr
  • 483
  • 1
  • 11
  • 23
  • Worth noting that JavaScript doesn't have classes in the sense that class-based OOP languages like Java and C# do. JavaScript uses prototypical inheritance (an object has a reference to another object which is its prototype, from which it can inherit properties). What you have above is a *constructor function* (`zeros`) and associated object (`zeros.prototype`). You use it with `new`, which creates a new object backed by the object that `zeros.prototype` points to, then calls `zeros` with `this` referring to that new object. ES2015 adds `class`, which is primarily just more convenient syntax. – T.J. Crowder Feb 05 '16 at 18:18
  • Perhaps also worth noting that the overwhelming convention in JavaScript is to name constructor functions with an initial capital letter, e.g. `Zeros` rather than `zeros`, whereas other functions are (by convention) named with an initial lower-case letter. – T.J. Crowder Feb 05 '16 at 18:20
  • [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript#Custom_objects) has everything you need to know. – Felix Kling Feb 05 '16 at 18:21
  • Possible duplicate of [How does JavaScript .prototype work?](http://stackoverflow.com/questions/572897/how-does-javascript-prototype-work) –  Feb 05 '16 at 18:31

2 Answers2

6

Call it via the new keyword:

var heyJude = new zeros('...');
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
madox2
  • 49,493
  • 17
  • 99
  • 99
3

You need to initialize the object using the new operator

This will instantiate an instance of your zeros class.

var heyJude = new zeros('110.....

Taken from MDN (modified for context):

When the code new zeros(...) is executed, the following things happen:

  1. A new object is created, inheriting from zeros.prototype.
  2. The constructor function zeros is called with the specified arguments and this bound to the newly created object. new zeros is equivalent to new zeros(), i.e. if no argument list is specified, zeros is called without arguments.
  3. The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn't explicitly return an object, the object created in step 1 is used instead. (Normally constructors don't return a value, but they can choose to do so if they want to override the normal object creation process.)
Community
  • 1
  • 1
bluetoft
  • 5,373
  • 2
  • 23
  • 26