Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> If you define this.sayHi in the constructor, then each Person you create gets its own copy of the function, making every Person heavier in memory.

Does anyone know whether this is true for more sophisticated JS engines like v8? I seem to recall reading something like that, that it detects that it is the same function, but I might be misremembering it.



I don't know, but I would suspect it's still the case, because doing anything else would require a lot of analysis of the code's behavior. In order to safely merge all those definitions into one, the engine would have to know:

* That the function in question never accesses anything in its closure that could be different for each construction

* That hasOwnProperty() is never called on the object to check which way the method is declared (alternatively, remember that it had done this optimization, and spoof the return value)

* That the function is never used as a constructor. Otherwise, Person could update sayHi's prototype and wind up changing its effects for all Persons, where it was supposed to create a customized inner class.

And if you think any of these are easy, remember that you can get a pointer to that function via the following:

  var a = 'say', b = 'hi'
  var sayHi = (new Person)[a + b]




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: