www.webdeveloper.com
Results 1 to 10 of 10

Thread: prototype and constructor in javascript.

  1. #1
    Join Date
    Sep 2013
    Posts
    2

    prototype and constructor in javascript.

    Hello developers

    This is Sri.
    i am having a hard time in understanding Prototype and Constructor in Javascript.

    Can anyone please clarify my doubts.

    1. What does mean by Prototype in Javascript?
    2. What is Constructor?
    3. what are the uses of Prototype and Constructor JS?
    4. why do we use Prototype and constructor in JS?



    Thanks in advance.

  2. #2
    Join Date
    Oct 2012
    Location
    Croatia
    Posts
    240
    I'm not an expert, I'm still learning but I'll try to explain it to you and if I'm wrong let someone correct me.

    JavaScript is an Object based language. So you have objects like String, Array, Number, Math... All this objects have some properties and methods you can use.
    But what if you want to build one of your own? Let's say you are building an application for some car shop. You want to be able to add buyer's details like for example:

    1. his/hers name and surname
    2. his/hers city/street address
    3. car model
    4. car price
    5. car color

    etc...

    JavaScript obviously doesn't come with an object that let's you do that (actually you can do it on number of different ways but pretend that you can't).

    So you may define a reference type which we'll call simple "CustomerDetails()". What are reference types? Reference types are simply templates for your objects as arhitect's drawings are templates used to build a house. One thing to note here is that some developers refer to reference types as classes and use this two terms interchangeably. While this is correct for object-oriented languages such as C#, C++, Java... this is not correct for JavaScript as JavaScript has no formal class construct although it has support for reference types (logical equivalent to classes).

    A reference type consist of three things:

    1. A constructor
    2. Method definitions
    3. Properties

    How do you define it?

    Code:
    function CustomerDetails() {}
    At first this may look like the same definition you are using when defining new functions. It's correct until you start to add some properties and methods to it.

    So lets do that

    Code:
    function CustomerDetails()
    { 
    var custName;
    var custSurname:
    var custCarModel;
    var carPrice;
    var carColor;
    }
    Now you have defined your template for CustomerDetails object. So how do you add properties and methods to it? Simply by using prototype property. Prototype property let's you add properties and methods to objects. So let's add some methods and properties to our CustomerDetails reference type.

    Code:
    CustomerDetails.prototype.setCustName = function(cName)
    {
    this.custName = cName;
    }
    
    CustomerDetails.prototype.setCustSur = function(cSurname)
    {
    this.custSurname = cSurname;
    }
    ...
    How do you get values from your variables?

    Code:
    CustomerDetails.prototype.getCustName = function()
    {
    return this.custName;
    }
    
    CustomerDetails.prototype.getCustSur = function()
    {
    return this.custSurname;
    }
    ...
    In the code above "this" keyword referes to that object instace of your reference type.

    So now that you have defined all of your methods and properties you have to be aware of one more thing. JavaScript won't create an object until you say so.

    How do you tell JavaScript to create an instace of object?

    Code:
    var custDetails = new CustomerDetails();
    Word new simply tells JavaScript to create new Object while CustomerDetails() is the constructor for that object (the one that you have built up). Now that you have created an instance of your object you can use it's properties and methods like with any other object in JavaScript (String, Array, Number...). So let's do that

    Code:
    var custDetails = new CustomerDetails();
    
    custDetails.setCustName("name");
    custDetails.setCustSur("surname");
    
    document.write("Your name is " + custDetails.getCustName() + " and your surname is " + custDetails.getCustSur())
    The output will looke like this:

    Your name is name and your surname is surname.

    Hope this one will help you out.
    Last edited by tech_soul8; 09-12-2013 at 08:57 AM.

  3. #3
    Join Date
    Oct 2012
    Location
    Croatia
    Posts
    240
    ...btw built-in objects such as String, Array, Number... are also reference types and you create an instance of them using the new method and constructor name.
    Code:
    var myarray = new Array()

  4. #4
    Join Date
    Sep 2013
    Posts
    2
    hii tech_soul8

    thanks a lot...giving the clear idea about the prototypes and constructors.


    what does below code implies?


    Code:
    function Person(){
    }
    Person.prototype = {
    constructor: Person,
    name : “Nicholas”,
    age : 29,
    job : “Software Engineer”,
    sayName : function () {
    alert(this.name);
    }
    };

  5. #5
    Join Date
    Oct 2012
    Location
    Croatia
    Posts
    240
    Well... firstly I have to remind you that I'm not an expert too . Secondly reference types are some pretty advanced stuff in JavaScript. Thirdly I have never seen syntax like that before but... if you look at it more closely you'll see next:

    Code:
    function Person(){
    }
    is the same as

    Code:
    function CustomerDetails() {}
    and it is used to define your reference type.

    The next block of code looks like this:

    Code:
    Person.prototype = {
    constructor: Person,
    name : “Nicholas”,
    age : 29,
    job : “Software Engineer”,
    sayName : function () {
    alert(this.name);
    }
    and it is the same as if you have wrote it like this

    Code:
    Person.prototype.getName = function ()
    {
    return this.name;
    }
    So if you use this syntax

    Code:
    function Person(){
    }
    Person.prototype = {
    constructor: Person,
    name : “Nicholas”,
    age : 29,
    job : “Software Engineer”,
    sayName : function () {
    alert(this.name);
    }
    };
    You'll get an alert box with "Nicholas" name inside it.

    If you're wondering how to run the code and why did you get "Nicholas" look at this

    Code:
    function Person(){
    }
    Person.prototype = {
    constructor: Person,
    name : “Nicholas”,
    age : 29,
    job : “Software Engineer”,
    sayName : function () {
    alert(this.name);
    }
    };
    
    var perName = new Person();
    perName.sayName();
    So you declare new variable and call it perName. You initialize this variable by creating a new object with the new keyword and with the Person constructor for that object. Recall from previous post that in this case Person is the constructor you are calling when you want JavaScript to create a new object that you have defined.

    By setting your variable (perName) to reference your Person object you can call it's properties and methods and that's exactly what you did by typing the following:

    Code:
    perName.sayName();
    So for example if you want to change former code to show how old "Nicholas" is you have to change the last line of code to look like this

    Code:
    alert(this.age);
    And for the end just to try to make it more clear to you if you didn't understand it yet you could also rewrite your code to look like the example for the CustomerDetails().

    Code:
    function Person()
    {
    var name;
    var age;
    var job;
    }
    
    Person.prototype.setName = function(perName)
    {
    this.name = perName;
    }
    
    Person.prototype.setAge = function(perAge)
    {
    this.age = perAge;
    }
    
    Person.prototype.setJob = function(perJob)
    {
    this.job = perJob;
    }
    
    Person.prototype.sayName = function()
    {
    return this.name;
    }
    So what you get is the same result, difference is only in syntax you use. Although it looks like if you go with my example you'll have to type more lines of code but that's the way I do it when it comes to reference types.

    Hope things are now more clear to you.
    Last edited by tech_soul8; 09-12-2013 at 01:38 PM.

  6. #6
    Join Date
    Sep 2013
    Posts
    3
    Hello, I just registered here. Is it possible to get help with a sophomore level Java program? I have worked on it for three days and I cannot get it. Thanks to anyone who can help.

  7. #7
    Join Date
    Oct 2012
    Location
    Croatia
    Posts
    240
    Code:
    ...
    name : “Nicholas”
    ...

    same as:


    Code:
    Person.prototype.setName = function(perName)
    {
    this.name = perName;
    }

    etc...

  8. #8
    Join Date
    Oct 2012
    Location
    Croatia
    Posts
    240
    Or you could also write it like this:


    Code:
    Person.prototype.setName = function()
    {
    this.name = "Nicholas";
    }

    Above code is really clumsy because to set name you have to call the function but I just gave you an example to see number of ways you can do it (as with the everything else in programming in general).

    Much better solution and the most close one to your example but on my way would be:


    Code:
    function Person()
    {
    this.name = "Nicholas";
    }

    As you can see there are really number of ways to do the same thing on many different ways.

  9. #9
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,330
    Minor correction to your code...
    Code:
    Person.prototype = {
      constructor: Person, 
      name : “Nicholas”,  // problem with these quotes
      age : 29,
      job : “Software Engineer”,  // and again, problem with these quote characters
      sayName : function () { alert(this.name); }
    };
    
    // should be written with "real" text quotes, not the wordprocessor paired quote characters.
    Person.prototype = {
      constructor: Person, 
      name : "Nicholas",
      age : 29,
      job : "Software Engineer",
      sayName : function () { alert(this.name); }
    };


    Sample code with modification assignments...
    Code:
    <!DOCTYPE HTML>
    <html>
    <head>
    <title> Untitled </title>
    <meta charset="utf-8">
    
    </head>
    <body>
    <pre id="debug"></pre>
    
    <script type="text/javascript">
    // Modified from post #13
    // on: http://www.webdeveloper.com/forum/showthread.php?283505-prototype-and-constructor-in-javascript
    
    function Person(){}
    Person.prototype = {
      constructor: Person,
      Pname : "Nicholas",
      age : 29,
      job : "Software Engineer",
      sayName : function (IDS) {
        var str = '<p>'+this.Pname+' is a '+this.age+' year old '+this.job;
        document.getElementById(IDS).innerHTML += str;
      }
    };
    
    var perName = new Person();
    perName.sayName('debug');
    
    // can also modify original entry
    perName.Pname = 'Mary';
    perName.age = 23;
    perName.job = 'runway model';
    perName.sayName('debug');
    
    </script>
    
    </body>
    </html>
    Last edited by JMRKER; 09-12-2013 at 02:09 PM.

  10. #10
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,330
    Quote Originally Posted by DemonToe View Post
    Hello, I just registered here. Is it possible to get help with a sophomore level Java program? I have worked on it for three days and I cannot get it. Thanks to anyone who can help.
    Welcome to the forums, but you might get better help from the correct forum.
    This is the JavaSCRIPT forum, not the Java forum.

    Might request the moderator move your query.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles