JavaScript: Understanding Prototype and Class methods

So, in JavaScript, first of all, its an object oriented programming but without classes (till ES5), now with ES6 we have classes officially in JavaScript

But still the old behaviour of the language is forwarded with newer version

In Javascript creating an object is possible via its functions( new [Func]()), function is a first class (can be passed as an argument), function is a high order function(can be received as an argument), function it self acts a constructor( new func() )

take a look at below code

  
  function User(name, passwd) {
    this.name = name;
    this.passwd = passwd;
    this.methodname = "User"
  }

  u1 = new User("User1", "Password")
  u2 = new User("User2", "Password")

  console.log(u1)
  console.log(u2)

  User.prototype.method1 = function () {
    console.log("This is method1");
  }
  u1.method1()

  User.method2 = function() {
    console.log("this is method2");
  }
  User.method2()

  

explanation is as follows

  • We have defined a function called `User`
  • Created two objects from that function( Yes, in JS you can do that, function will now work a constrctor
  • Now if you look at console.log output u1 and u2 objects will contain the data, which are passed as argument to function
  • till now all good, then here comes interesting part, `prototype`, using prototype keyword, you are defining a new function called `method1`
  • this method1 function created after creating object u1, u2, but still because its a prototype method where JS will update its reference automatically to all existing objects, u1 and u2 objects can access that method
  • So, how's that happening ?, if you look u1 object structure, in console.log, you will a reference to User.prototype,so when ever a new method added to User.prototype, automatically its available for u1 object via path
  • But then we have defined a method called method2(), and this is defined at class level, so only the User function/constuctor can access that but not the objects like u1, u2
  • the reason isnt like its defined after you have created objects, the reason is its just not under the scope for objects, its under the scope of construtor only.
  • You can use this trick in Javascript, that if you have a method and you dont want that method to be available to your object, then create the method like method2

There is so much to say about prototype and class methods, but I believe this simple read might be helpful

Hope it helps

Thank you.

Comments

Popular posts from this blog

grep: unknown device method

Uploading files to FTP/SFTP using CURL

How to find outgoing IP in Linux ?