- Set Object Properties and Functions on the Object’s Prototype
If you have some experience setting up classes in an object-oriented language like Python or Ruby, you understand that you write all your instance methods inside the class definition. Here’s the timeless example of the Person class, written in Ruby:
As I understand it, the code inside #initialize will set a ‘name’ instance variable for any instance of Person that you create, and when you call a method like #say_name the Person class is scanned for the method and used with the instance variables.
In this case, no other instance of Person will know how to say its name unless you explicitly tell it so.
Here I’ve set a few more properties on the prototype, just to illustrate that you can use this feature to set properties and functions that you want to be common across all Person objects. Inside of sayName, I’ve used ‘this’ to refer to the object currently being sent the message to call its sayName function. This method of setting properties on the prototype means that you can save time (during object construction) and memory space (because the properties will only be saved in one place).
2. Avoid Creating Nested Closures
If you don’t know what a closure is, I’ll try to provide a simple example and a little bit of an explanation. I’m not much of an expert on the subject, though, so definitely do more research on your own to get a more thorough understanding of how they work, if my explanation is not quite enough. I remember how strange this concept was when I first came across it, so take a little while to let it sink in.
Another way that people usually explain closures is that you can use them to create a kind of “function factory,” a function that creates other customized functions. Here’s a trivial one that creates functions that carry out the basic arithmetic operators:
As you can see, each version of mathFunc that we call ‘remembers’ what the variable ‘operator’ was in its own context, and uses that to operate differently on the same arguments.
3. Avoid Lengthy Scope Chain Searches
The greater the difference between current level and level in which the variable was originally defined, the longer the lookup time will be.