0

Hoping someone can provide an explain-like-I’m-five elucidation of the difference between the following types of functions within Famo.us, and when it’s appropriate to use them:

sampleFunction() {}

_sampleFunction() {}

SampleView.prototype.sampleFunction() {}

.bind and .call are also thrown around a lot…I understand them vaguely but not as concretely as I’d like. That might be a different question, but please feel free to use them in your explanation!

Apologies for the vagueness...wish there was more regarding this in famo.us university.

Sam Seidenberg
  • 153
  • 1
  • 7
  • Search for the specific questions: e.g. call/apply are well covered, as are prototypes. As for the leading underscore, it means nothing to JavaScript itself but may be a convention (in Famo.us). – user2864740 Jul 17 '14 at 20:07

1 Answers1

2

None of what you're looking at is syntax specific to Famo.us. It's actually common, if intermediate level, VanillaJS.

The _ is simply a coding convention to denote that a specific function should belong to the parent scope (ie a member/private function, whatever you prefer to call it). Javascript doesn't really have support for encapsulation - the act of blocking other classes and objects from accessing another class's functions and variables. While it is possible, it's quite cumbersome and hacky.

You'll see that Famo.us uses the underscore convention to denote that a function is a member of the class using it. Some of these functions are actually just aliases to the actual Javascript native function, for example ._add actually just call's Javascript's .add method. Of course, ._add could be updated in the future on Famo.us's end to do more in the future if that's required. You really wouldn't want to try and write over the native Javascript add. That's super bad.

The other upshot is that you can document that class and say that you can and should use the _add method for a specific purpose/scenario. You'll see that in the API docs.

Understanding prototype is a core part of what it means to be a Javascript Programmer, after all, it is a prototype driven language. MDN has a much better explanation than anything I can offer here but it's basically at the core of your classes.

If you want to extend off of an existing class (say, create your own View or Surface type) you would extend it's prototype. Check out Famous Starter Kit's App examples and see how many of them create an "AppView" class, which takes the prototype of the core View, copies it for itself, and then adds it's own functions, thus extending View without ruining the original copy.

Kraig Walker
  • 812
  • 13
  • 25