In JS, a function is an object. It takes time to get used to it, but it is true. Throw it a little, and the code that you see others will make sense. If you saw Javascript where people pass the function () {} as a parameter to another function, this is proof that the functions are first class objects.
Once you can wrap yourself around (it took me a while), you need to understand that if you create a function, you can get a new instance. See the following 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");
At this point, you have two examples of the FooName method: n1 and n2. This is a kind of convention in JS to call your effective function the first letter of the top level, and not the lower case letter of the client. In this example, I indicate that my function can be set by naming FooName instead of fooName. I hope this makes sense.
In the above example, n1 has three properties. The private name property, the public setName property, and the public getName property. Each time I create a new FooName, a copy of getName and setName will be created. This may lose memory space. Since getName and setName will not change, I do not need a new copy for each instance of FooName. Prototypes appear here.
You can say the following, and then getName and setName will exist only once in memory, freeing memory, which is good.
FooName.prototype.setName = function(n){ this.name = n; } FooName.prototype.getName = function(){ return this.name; }
If you remove getName and setName from the FooName function, now you will have FooName "class", which has two methods: getName and setName.
Play with him. Let me know if you have any questions.
frosty
source share