-2

At generator.prototype.__proto__.math, the function's argument sets e = 0. However, when the gen.math(1) is called, the value for e seems to be set to 1 instead of 0. Is the initial e = 0 overwritten by gen.math(1) or is there something more?

function * generator() {
  yield 1;
}

generator.prototype.__proto__.math = function(e = 0) {
  return e * Math.PI;
}

generator.prototype.__proto__; 

const gen = generator();
gen.math(1); // 3.141592653589793
SergGr
  • 23,570
  • 2
  • 30
  • 51
Revircs
  • 1,312
  • 3
  • 12
  • 23

2 Answers2

1

I don't think this behavior has anything to do with generators at all. Your code is essentially equivalent to

const math = function(e = 0) {
  return e * Math.PI;
};

math(1);

The syntax you use for e = 0 is a syntax for Default parameters. It doesn't override the supplied parameters. All it does is provide values if parameters have not been supplied. So you can do

math()

and get 0.

If you want to ignore argument value you can easily do it in our function body. If your case is more complicated, you might need to use bind to set values for parameters.

SergGr
  • 23,570
  • 2
  • 30
  • 51
1

To answer your question first, function(e = 0) is defining a function with a default argument of e=0. This means that if e is not provided, it will default to a value of 0. For example, when you call just math().

You're calling math(1), which will pass a value for e - thus the default will not apply. e will simply be the passed in value, which is 1.

I also want to caution you about modifying __proto__ - the line you've set up:

generator.prototype.__proto__.math = function(e = 0);

Is actually defining math on the prototype of all Generators. You likely didn't intend for this to happen, I assume.

See __proto__'s documentation for more information, and take heed of all of the big red boxes at the top please. :)

Sean Johnson
  • 5,567
  • 2
  • 17
  • 22