I've always seen examples of Class.prototype.method, but never instances of this.prototype.method. For example:
function Class() { this.prototype.method = function() { alert("is this allowed?"); }; }
vs
function Class() {} Class.prototype.method = function() { alert("traditional example"); };
In most cases they are essentially the same, but the second version saves memory because there is only one instance of the function instead of a separate function for each object.
Definition. A class is a template for creating or instantiating objects within a program while a method is a function that exposes the behavior of an object. Thus, this is the main difference between class and method.
prototype is a property of a Function object. It is the prototype of objects constructed by that function. __proto__ is an internal property of an object, pointing to its prototype. Current standards provide an equivalent Object.
Classical inheritance is limited to classes inheriting from other classes. However prototypal inheritance includes not only prototypes inheriting from other prototypes but also objects inheriting from prototypes.
Does this.prototype exist?
No. But, this.constructor.prototype
should.
Is it the same as Class(.constructor).prototype?
It will generally have the same value (so long as this.constructor === Class
), but not the same intent.
What about inheritance?
Each new Class
instance will inherit from Class.prototype
. So, a prototype
object is good for defining shared values accessible to all instances. Then, the constructor just has to setup state that's unique to each instance.
But, attempting to mix the 2 and set a prototype
property within the constructor has a few problems, including a chicken-or-egg conflict as the method won't exist until the first instance is created:
function Class() { this.constructor.prototype.method = function () {}; } console.log(typeof Class.prototype.method); // "undefined" var a = new Class(); console.log(typeof Class.prototype.method); // "function"
And defeats some of the benefit of having the prototype
as the method is being recreated with each additional instance:
var method = a.method; console.log(a.method === method); // true var b = new Class(); console.log(a.method === method); // false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With