loading...

What are all of JavaScript's "Magic Methods" or semi-implementation of them?

calin92540842 profile image PDS OWNER CALIN (Calin Baenen) ・1 min read

So I had a run-in with JavaScript's Symbol() just now as of making this, this website (https://www.javascripture.com/Iterable) what actually happens when JavaScript, and it appears:

Symbol.iterator

is almost the same as Python's magic method:

class Example:
    def __iter__():
        # Code to make iteration here
        return

so this begs the question, atleast for me, are there any more "Magic Methods" in JavaScript, similar to Python's

__dict__
__iadd__
#etc...

etc...?

Thanks!
Cheers!

Discussion

markdown guide
 

Similar to Symbol you can use the * after function name to create iterator/generator.

function* iterate(max=10) { 
  for (x=1; x <= max; x++) {
    yield x;
  }  
}

var my5List = iterate(5);
my5List.next(); // 1
 
 

A true magician never reveals his tricks. JS has a few of them hidden way up its sleeves...