1

For example:

function Car () {
    this.x = 0;
}

Car.prototype.go = function () {
    this.x += 20;
}

var car = new Car();
car.go(); // adds 20 to car.x, not car.prototype.x??

Does this have to do with the new keyword? How exactly does the new keyword interact with the prototype?? The prototype exists before I called the new keyword, so I'm curious how the new keyword grabs the context and applies it to prototype's functions

neaumusic
  • 8,193
  • 7
  • 41
  • 65
  • It "copies" it to the new object. – zerkms Sep 21 '15 at 23:15
  • no it doesn't though, because there would be no point in having prototypal shared functions if they were copied – neaumusic Sep 21 '15 at 23:16
  • There would be: references are "copied". `var a = {}; var b = a;` here are the 2 "copies" of the same reference that refer to the same object. – zerkms Sep 21 '15 at 23:16
  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain – zerkms Sep 21 '15 at 23:19

1 Answers1

2

This is nothing to do with prototypes; it's just how function calls work. If you call a function as one.two.three, this becomes one.two.

var foo = { a: function() { this.b = 20; } };
foo.a();
console.log(foo);

It doesn't matter where/how the function was defined, only how it was called. (Try calling Car.prototype.go() directly and see what happens.)

See also: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

Eevee
  • 43,129
  • 10
  • 82
  • 119