Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does JavaScript .prototype work?

I'm not that into dynamic programming languages but I've written my fair share of JavaScript code. I never really got my head around this prototype-based programming, does any one know how this works?

var obj = new Object(); obj.prototype.test = function() { alert('Hello?'); }; var obj2 = new obj(); obj2.test(); 

I remember a lot discussion I had with people a while back (I'm not exactly sure what I'm doing) but as I understand it, there's no concept of a class. It's just an object, and instances of those objects are clones of the original, right?

But what is the exact purpose of this ".prototype" property in JavaScript? How does it relate to instantiating objects?

Update: correct way

var obj = new Object(); // not a functional object obj.prototype.test = function() { alert('Hello?'); }; // this is wrong!  function MyObject() {} // a first class functional object MyObject.prototype.test = function() { alert('OK'); } // OK 

Also these slides really helped a lot.

like image 734
John Leidegren Avatar asked Feb 21 '09 12:02

John Leidegren


People also ask

What does .prototype do in JavaScript?

The prototype is an object that is associated with every functions and objects by default in JavaScript, where function's prototype property is accessible and modifiable and object's prototype property (aka attribute) is not visible. Every function includes prototype object by default.

How does JavaScript inheritance work?

When it comes to inheritance, JavaScript only has one construct: objects. Each object has a private property which holds a link to another object called its prototype. That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype.

How does prototypal inheritance work?

The Prototypal Inheritance is a feature in javascript used to add methods and properties in objects. It is a method by which an object can inherit the properties and methods of another object. Traditionally, in order to get and set the [[Prototype]] of an object, we use Object. getPrototypeOf and Object.

What is prototype chaining in JavaScript?

That means all the objects in JavaScript, inherit the properties and methods from Object. prototype. This is called Prototype chaining. This is a very powerful and potentially dangerous mechanism to override or extend object behavior. Objects created using new keyword, inherit from a prototype called Object.


1 Answers

In a language implementing classical inheritance like Java, C# or C++ you start by creating a class--a blueprint for your objects--and then you can create new objects from that class or you can extend the class, defining a new class that augments the original class.

In JavaScript you first create an object (there is no concept of class), then you can augment your own object or create new objects from it. It's not difficult, but a little foreign and hard to metabolize for somebody used to the classical way.

Example:

//Define a functional object to hold persons in JavaScript  var Person = function(name) {    this.name = name;  };    //Add dynamically to the already defined object a new getter  Person.prototype.getName = function() {    return this.name;  };    //Create a new object of type Person  var john = new Person("John");    //Try the getter  alert(john.getName());    //If now I modify person, also John gets the updates  Person.prototype.sayMyName = function() {    alert('Hello, my name is ' + this.getName());  };    //Call the new method on john  john.sayMyName();

Until now I've been extending the base object, now I create another object and then inheriting from Person.

//Create a new object of type Customer by defining its constructor. It's not  //related to Person for now. var Customer = function(name) {     this.name = name; };  //Now I link the objects and to do so, we link the prototype of Customer to  //a new instance of Person. The prototype is the base that will be used to  //construct all new instances and also, will modify dynamically all already  //constructed objects because in JavaScript objects retain a pointer to the  //prototype Customer.prototype = new Person();       //Now I can call the methods of Person on the Customer, let's try, first  //I need to create a Customer. var myCustomer = new Customer('Dream Inc.'); myCustomer.sayMyName();  //If I add new methods to Person, they will be added to Customer, but if I //add new methods to Customer they won't be added to Person. Example: Customer.prototype.setAmountDue = function(amountDue) {     this.amountDue = amountDue; }; Customer.prototype.getAmountDue = function() {     return this.amountDue; };  //Let's try:        myCustomer.setAmountDue(2000); alert(myCustomer.getAmountDue()); 

var Person = function (name) {      this.name = name;  };  Person.prototype.getName = function () {      return this.name;  };  var john = new Person("John");  alert(john.getName());  Person.prototype.sayMyName = function () {      alert('Hello, my name is ' + this.getName());  };  john.sayMyName();  var Customer = function (name) {      this.name = name;  };  Customer.prototype = new Person();    var myCustomer = new Customer('Dream Inc.');  myCustomer.sayMyName();  Customer.prototype.setAmountDue = function (amountDue) {      this.amountDue = amountDue;  };  Customer.prototype.getAmountDue = function () {      return this.amountDue;  };  myCustomer.setAmountDue(2000);  alert(myCustomer.getAmountDue());

While as said I can't call setAmountDue(), getAmountDue() on a Person.

//The following statement generates an error. john.setAmountDue(1000); 
like image 165
stivlo Avatar answered Oct 19 '22 09:10

stivlo