Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In JS, a function is an Object. It takes a while to get used to that, but it is true. Throw that around for a bit and the code that you see others using will make sense more. If you have seen Javascript where people are passing a function(){} as a parameter to another function, that is proof that functions are first class objects. </p> <p>Once you can wrap your head around that (it took me a while) then you need to understand that if you make a function, you can get a New instance of it. See the following code:</p> <pre><code>function FooName(){ var name; this.setName = function(n){ this.name = n; } this.getName = function(){ return this.name; } } var n1 = new FooName(); var n2 = new FooName(); n1.setName("FOO"); n2.setName("BAR"); </code></pre> <p>At this point you have two instances of the FooName method: n1 and n2. It is kind of a convention in JS to name your instantiable function with an Uppercase first letter, instead of the customer lowercase first letter. In this example, I indication that my function can be instanced by naming it FooName instead of fooName. I hope this makes sense. </p> <p>In the example above, n1 has three properties. A private name property, a public setName property, and a public getName property. Each time I instantiate a new FooName, a copy of getName and setName are going to be created. That can waste space in memory. Since the getName and setName isn't going to change, I don't need a new copy of it for each FooName instance. This is where prototypes come in. </p> <p>You can say the following, and then getName and setName will only exist once in memory, thus freeing up memory, which is a good thing. </p> <pre><code>FooName.prototype.setName = function(n){ this.name = n; } FooName.prototype.getName = function(){ return this.name; } </code></pre> <p>If you remove the getName and setName from the FooName function, then now you will have a FooName "class" that has two methods, getName and setName. </p> <p>Play with it. Let me know if you have questions. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload