3 ms·
This made no sense to me at all, but I suspect that I may have a deeper misunderstanding of what it's trying to say: "Assigning a member function to a prototyp
by flatline 16y ago
This made no sense to me at all, but I suspect that I may have a deeper misunderstanding of what it's trying to say:
"Assigning a member function to a prototype should not be confused with assigning an anonymous function to a member variable of a class, which only adds the function to a particular instance of the class"
I thought that by setting this.somefn = function() { blah; }; in the constructor, you are adding the function to the prototype of the object, with the name "somefn". At least, I have implemented a fair amount of code this way and used classical JS inheritance without any apparent issues, I would like to know what the difference is both practically and theoretically.
- v413 16y agoLets compare the constructor: function A () { this.helloWorld = function () {return 'hello world'}; }; a = new A(); vs. function B () {}; B.prototype.helloWorld = function () {return 'hello world'}; b = new B(); Both constructors achieve the same result - their instances a and b both have the methods helloWorld. Some of the differences are: 1. With constructor A, whenever you create a new instance, you create a new function, hence you have both performance and memory inefficiencies. With Constructor B, the helloWorld function is created just once, and every instance of B automatically inherits this single instance of the function helloWorld, hence we have performance and memory efficiency. 2. Using inheritance through the prototype of the constructor functions also gives more flexibility and simplicity in sharing common functions and modules.
- solutionyogi 16y agoAs v413 wrote, the main difference is how the function is linked to the instance. If you define a member function inside the constructor, that member function is assigned to each and every object separately. The function code is not shared across all instances. This is extremely unintuitive if you are coming from a statically typed OOP language like Java/C#. To get a behavior similar to what Java/C# gives you, you should use prototype. To demonstrate the concept, I created this code example: http://jsbin.com/utuso3/edit http://jsbin.com/utuso3/edit [Click on 'Preview' button to run the example code] I hope that made sense.
- flatline 16y agoThanks (and to v413), this does make sense. I hadn't thought it through that each call to the constructor will create a new function object, which was pretty apparent once stated and I re-examined the code.