0

Specifically, I don't understand why some methods require a .prototype in front of them but others to not. I was practising a code where a correct answer was

var Foo = function(value) {
  this.val = value;
}

Foo.prototype.valueOf = function() {
  return this.val;
}

and I am wondering why the prototype in Foo.prototype.valueOf was needed, why can you not simply just do Foo.valueOf? It is what I did before with other prototypes. For example, I do x.slice(2,4) and not x.prototype.slice(2,4).

Ry-
  • 218,210
  • 55
  • 464
  • 476
user3813774
  • 93
  • 1
  • 6
  • 3
    Before anything could be explained about this, you should first understand the difference between **adding/setting a method** and **calling an already existing method.** – The Paramagnetic Croissant Jul 07 '14 at 19:46
  • Short answer: You can! Both work and are valid JavaScript Long answer: The .prototype way is a preferred way of defining *methods* for an object *constructor* because in that way, all methods are shared between instances created with that constructor instead of being redefined each time, which would be somewhat more memory intensive (and might have a performance benefit in modern browsers, who tend to search for methods first in an object's prototype). – Pablo Mescher Jul 07 '14 at 19:50
  • the valueOf() drills into the object to return just the val property instead of the whole object. – dandavis Jul 07 '14 at 19:55
  • If you'd like to know more about how prototype is used by JavaScript then the following answer may help you out: http://stackoverflow.com/a/16063711/1641941 – HMR Jul 08 '14 at 02:39

1 Answers1

0

Foo is a constructor function. If you wanted to call Foo.valueOf like x.slice, you could set Foo.valueOf, but that’s not what this code accomplishes; it says that any object constructed using Foo should inherit the valueOf defined there. So:

var x = new Foo(42);
x.valueOf() === 42 // true
Ry-
  • 218,210
  • 55
  • 464
  • 476