Search code examples
javascriptenumerated-types

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


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.


Solution

  • 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?