Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class.prototype.method vs this.prototype.method

Tags:

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"); }; 
  1. Does this.prototype exist?
  2. Is it the same as Class.prototype?
  3. What about inheritance?
like image 235
00500005 Avatar asked Mar 02 '14 04:03

00500005


People also ask

Is .prototype same as this?

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.

What is difference between class and method?

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.

What is difference between __ proto __ and prototype?

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.

What is the difference between prototypal and classical inheritance?

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.


1 Answers

  1. Does this.prototype exist?

    No. But, this.constructor.prototype should.

  2. 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.

  3. 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 
like image 84
Jonathan Lonowski Avatar answered Sep 27 '22 18:09

Jonathan Lonowski