Example: Enumerated Types ("JavaScript, O'Reilly Publishing")

44 Views Asked by At

Has anyone read "JavaScript, The Definitive Guide" (O'Reilly)?

I spent several hours digesting Example 9-7.

In particular, the .foreach() "class" method has me somewhat puzzled.

Also, does .valueOf get called automatically?

Thank you in advance.

2

There are 2 best solutions below

0
philipp On BEST ANSWER

Also, does .valueOf get called automatically?

valueOf and toString are called "automatically". valueOf if the object i question is converted to a number, and toString, well, if it is converted to a string.

function Foo(){}

Foo.prototype = {
  constructor: Foo,
  valueOf: function() { return 2; },
  toString: function () { return 'bar' }
}

var f = new Foo();
f + f + 2 //6
'' + f   //"bar"

But if you would have read the book, you should know that already.

In particular, the .foreach() "class" method has me somewhat puzzled.

Why? It is a member of Array.prototype, well documented and extremly handy. Or do you refering to another example?

0
Danilo Miranda On

In a simple way you can use the forEach like this:

var a = [1, 2, 3];

a.forEach(function(number) {
  console.log(number);
});

You don't have to use something like valueOf, the parameter of that function is already the value itself.