3

I have gone through plenty of Stack Overflow question that had description but I seriously found them very confusing. What I want is a simple explanation,please don't refer a link.

I'm totally confused, completely jumbled up between:

  • Prototypes,

  • Objects,

  • Constructor

I have done plenty of research but I found them very complicated.

Any simple explanation??

  • 3
    Did you ever googled them ? Read [this](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript?redirectlocale=en-US&redirectslug=JavaScript%2FA_re-introduction_to_JavaScript). – AllTooSir May 30 '13 at 11:55
  • yes!!i went through a lot of them,i got familiarised with the suyntax,but i din`t got the concept thoroughly,evrything is still very vague in my mind –  May 30 '13 at 12:00
  • You need to be more specific what exactly is it that you don't understand. Otherwise it's very hard to do anything other than repeat what is said everywhere else. – JJJ May 30 '13 at 12:01
  • 1
    This is too big of a question for the StackOverflow format. You will need to break your questions into something smaller. OOP in javascript takes about a book to explain, and just Prototype use takes at least an entire chapter. Is there something specific about the prototypes that doesn't make sense? – MatthewMartin May 30 '13 at 12:02
  • I guess time to read a good JS book. Refer JS Page at stackoverflow [http://stackoverflow.com/tags/javascript/info] for references – closure May 30 '13 at 12:04
  • Yes,just wait 2 min.i ll simplify the question –  May 30 '13 at 12:04
  • what is the difference between prototype and constructor? –  May 30 '13 at 12:06
  • http://blog.pluralsight.com/2013/03/19/understanding-javascript-prototypes/ Read this blog which might help you – Abhimanyu May 30 '13 at 12:13

4 Answers4

12

Okay, a whirlwind tour:

Objects

An object is a thing that has properties. Properties have names and values. The names are always strings (although we can write them without quotes most of the time), and the values can be anything JavaScript supports: Numbers, strings, booleans, null, undefined, or references to objects.

So:

var a = {
    propertyName: "property value"
};

a is a variable referring to an object, which has a property named propertyName, whose value is the string "property value".

Prototypes

An object (say, obj) can have another object (say, p) "behind" it, where p lends obj its properties unless obj has its own property with a given name. p is the prototype object of obj. This is easiest to understand with an example:

// Let's create an object `p` with a couple of properties, `x` and `y`
// This syntax is called an "object initializer" (aka "object literal")
var p = {
    x: "x on p",
    y: "y on p"
};

// Now, we'll create a new object, `obj`, using `p` as its prototype
var obj = Object.create(p);

// And that means if we ask `obj` for a property called `x`, since it doesn't
// have its **own** `x`, it asks `p` for it. (And the same with `y`)
console.log(obj.x); // "x on p"
console.log(obj.y); // "y on p"

// But we can give `obj` its *own* `x` instead if we want
obj.x = "x on obj";
console.log(obj.x); // "x on obj"
console.log(obj.y); // "y on p"

// Doing that to `obj` had no effect on `p`
console.log(p.x); // "x on p"
console.log(p.y); // "y on p"

A very, very important aspect of prototypes is that the connection between the objects is live. So if obj doesn't have a y property, every time we ask obj for y it goes and asks p. And so if we change p's value for y, that change shows up if we ask obj for it:

var p = {
    x: "x on p",
    y: "y on p"
};

var obj = Object.create(p);

console.log(obj.y); // "y on p"

p.y = "updated y on p";

console.log(obj.y); // "updated y on p"

This live connection is a vital thing. So again, think of it like this: We ask obj for the property y, and obj says "I don't have my own, so I'll go ask p for it and give you that."

Note: The Object.create function I've been using to create obj is new as ECMAScript5 (the spec update from a couple of years ago). We'll come back to another way to given an object a prototype further down.

The prototype for an object is currently always set when the object is created, and cannot be changed (I couldn't swap in a q instead of p above after creating obj). Above I'm using Object.create to do it (and below we'll talk about constructor functions). Until ECMAScript5 (ES5), there was no standard way to get the prototype of an object. ES5 gives us a way to do it now, called Object.getPrototypeOf, but still doesn't offer a way to change it. The next version, ES6, will take things a bit further.

Functions

Functions are units of code that do things. Functions are also objects, and so they can have properties, although in practice it's relatively rare to use properties on functions (other than call and apply, which we don't need to talk about here).

You can declare a function:

function foo() {
}

...or you can create one with an expression:

// An anonymous -- unnamed -- function assigned to variable `foo`
var foo = function() {
};

// A function named `f` assigned to variable `foo`
var foo = function f() {
};

Declarations and expressions are different. Function declarations are evaluated before any step-by-step code in the same scope is performed. Function expressions are evaluated as they're encountered in the step-by-step code, like all other expressions. (People sometime call this "hoisting" because it means that in effect, even if a function declaration is at the bottom of a scope, it happens as though it had been lifted -- hoisted -- to the top.)

Functions can have arguments:

// `a` and `b` are arguments
function sum(a, b) {
    console.log(a + b);
}

And they can have return values:

function sum(a, b) {
    return a + b;
}
console.log(sum(1, 2)); // "3"

If a function doesn't return something else, the result of calling the function is the value undefined.

Methods

JavaScript doesn't have methods. It only has functions — but that's all it really needs. But if you have a function assigned to an object property, and you call that function as part of an expression retrieving the property from the object, then something happens that makes JavaScript seem to have methods: The this keyword refers to that object within the function call. Again, an example works wonders:

// A blank object
var obj = {};

// Lets put a function on it as a property
obj.foo = function() {
    console.log("this is obj? " + this === obj);
};

// Let's call that function
obj.foo(); // "this is obj? true"

More on my blog:

Constructors

Constructor functions are used with the new keyword, and they're one of the ways you give an object a prototype. When you call a function via new, a new object is created, and assigned a prototype from the function's prototype property:

function Foo() {
}
Foo.prototype.x = "x on Foo.prototype";

var obj = new Foo();
console.log(obj.x); // "x on Foo.prototype"

Every function automatically has a prototype property, even though of course we don't use the vast majority of functions as constructors.

An important thing to note here: The prototype property of a function is just a boring old property. It isn't the prototype of any object until/unless that function is called via the new operator. The new operator uses the prototype property of the function to set the prototype of the new object when you call the function via new, but that's all.

It's worth mentioning that until ES5, constructor functions like the above were the only way you could create an object with a given prototype. But with ES5, we got Object.create, which opened up more patterns for how to use JavaScript. (It was always possible to create your own Object.create, by using a temporary function, and in fact that's exactly what some people did.) Some people don't like using the new keyword and the prototype property, they prefer to use a "builder" pattern where you just call a function and get back an object. JavaScript is so flexible that you can do that.


More to Explore

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
4

You're in luck. There's a very simple explanation:

Step One: Create an Object

Say you want to circle:

var circle = {};

Step Two: Give it Some Properties

A circle can be drawn, so let's create a property called draw:

circle.draw = function () {
    // drawing logic
};
  1. A property is simply a variable belonging to an object. A variable by itself is not a property.
  2. Properties and variables can hold any kind of data. Functions in JavaScript is data.
  3. When a property holds a function it's called a method.

Hence we have a method called draw belonging to the object circle.

Step Three: Extend an Object

Now I want a ball and a ball is kind of like a circle. So let's extend circle to create a ball:

var ball = Object.create(circle);
  1. Here we took the object circle and used it to create a new object called ball.
  2. The object ball now has all the properties of circle. So we can call ball.draw.
  3. The object circle is the prototype of ball.

Step Four: Give it Some Properties

Every ball has a radius, so let's give ours one:

ball.radius = 5;

Step Five: Create a Constructor

There's a problem here. Every time I want to create a new ball I extend circle and manually define the radius of the ball. Instead I would like a function to create the ball and give it a radius for me. This function is called a constructor:

function createBall(radius) {
    var ball = Object.create(circle);
    ball.radius = radius;
    return ball;
}

var baseball = createBall(5);
var basketball = createBall(10);

baseball.draw();
basketball.draw();

That's pretty much all you need to know about prototypes, objects and constructors.

Of course there's a lot more explanation but it's too much for one StackOverflow answer. I wrote a blog post on it, and I'm not planning to rewrite the same thing here. You should read my blog. It's worth it: http://aaditmshah.github.io/why-prototypal-inheritance-matters


Edit: Sure, I'll explain what happening in that code: http://cssdeck.com/labs/4ksohwya

First, scroll down to the very end:

window.addEventListener(
    'load',
    init(null),
    false);

When the page loads it executes init:

function init(images) {

    canvas= document.getElementById('s');
    ctx= canvas.getContext('2d');
    canvas.width= window.innerWidth;
    canvas.height=window.innerHeight;

    garden= new Garden();
    garden.initialize(canvas.width, canvas.height, 300);

    lerp(0,2000);

    time= new Date().getTime();
    interval = setInterval(_doit, 30);
}

The init function creates an instance of Garden (garden = new Garden();) and executes the initialize method of garden. It also calls the _doit function in intervals of 30 milliseconds.

initialize : function(width, height, size)  {
  this.width= width;
  this.height= height;
  this.grass= [];

  for(var i=0; i<size; i++ ) {
    var g= new Grass();
    g.initialize(
        width,
        height,
        50,      // min grass height 
        height*2/3, // max grass height
        20,     // grass max initial random angle 
        40      // max random angle for animation 
        );
    this.grass.push(g);
  }

  this.stars= [];
  for( i=0; i<this.num_stars; i++ )  {
    this.stars.push( Math.floor( Math.random()*(width-10)+5  ) );
    this.stars.push( Math.floor( Math.random()*(height-10)+5 ) );
  }
},

The initialize method of garden then creates some instances of Grass, calls their initialize methods and stores them in an array.

function _doit()    {

  ctx.fillStyle= gradient;
  ctx.fillRect(0,0,canvas.width,canvas.height);
  var ntime= new Date().getTime();
  var elapsed= ntime-time;
  garden.paint( ctx, elapsed );

  // lerp.
  if ( elapsed>nextLerpTime ) {
    lerpindex= Math.floor((elapsed-nextLerpTime)/nextLerpTime);
    if ( (elapsed-nextLerpTime)%nextLerpTime<lerpTime ) {
      lerp( (elapsed-nextLerpTime)%nextLerpTime, lerpTime );
    }
  }

}

The _doit function calls the paint function of garden, and the paint function of garden calls the paint function of each grass.


So here there are two constructors:

  1. Grass
  2. Garden

Here are the two prototypes:

  1. Grass.prototype
  2. Garden.prototype

Inside the init function we create a single instance of Garden (that's one object):

var garden= new Garden();

Inside the initialize method of garden we create multiple instances of Grass:

var g= new Grass();

That's it.

Aadit M Shah
  • 72,912
  • 30
  • 168
  • 299
  • Very nice, I like how you used the term constructor to indicate a function creating an object and _not_ a function using the `new` keyword. – Benjamin Gruenbaum May 30 '13 at 12:23
  • 1
    In JavaScript, it's best **not** to call a function a constructor if you don't call it via `new`. "Builder" (or less frequently "creator") is a better term, because the specification gives the term "constructor" a specific meaning. – T.J. Crowder May 30 '13 at 12:30
  • @T.J.Crowder I wouldn't give it any special label at all. I just used the term "constructor" for the sake of explanation. Personally, I prefer using the __prototypal pattern of prototypal inheritance__ over the __constructor pattern of prototypal inheritance__ that most people use. That's one of the things about JavaScript that I don't like: the constructor pattern. It's problematic and hides true the prototypal pattern. You should read my blog post if you haven't. I tried to explain prototypal inheritance as best as I could. Apparently Eric Elliot from Adobe thought it was a great article. =) – Aadit M Shah May 30 '13 at 12:46
  • @AaditMShah: I understand what you're doing, I'm just saying that it's best not to confuse matters by calling it a "constructor," because the language (via its spec) gives that term a *specific* (and different) meaning. I have no problem at all with the approach. One of the things I love about JS is that it's so flexible, you can take a more traditional prototypical approach to creating objects. The language can be used in multiple ways, which I love about it. – T.J. Crowder May 30 '13 at 12:55
  • @AaditMShah:hii,i liked your answer and went through your blog.now i can say that i do understand a little about prototypes,constructor and objects.the link below is an example of prototypical approach that you mentioned.I think that is the proper standard for writing any code.can you just tell me which are the constructors,prototypes and objects in that code,i promise i wont trouble u any more. http://cssdeck.com/labs/4ksohwya (things to look out for--function paint,initialize and the way they are called-can you just brief me about that) –  May 30 '13 at 14:24
  • @jayeshjain - Thank you. I saw the link you posted. Wow, that's an amazing animation. Anyway, I updated my answer to point out the constructors, prototypes and objects and to explained how the `initialize` and `paint` methods are called. Hope that helps. – Aadit M Shah May 30 '13 at 15:56
  • @T.J.Crowder - I understand your point of view, but I doubt people will get confused. Whether you call it a constructor, a builder or a creator in the end you have to understand prototypal inheritance. As long as you write legible code it doesn't matter. – Aadit M Shah May 30 '13 at 16:00
  • @AaditMShah:You are 20,i can`t believe it,you are WOW!!! Correct me if i am wrong, 1)---the instances that have been created--can i say that garden.initialize(canvas.width, canvas.height, 300); is constructor declaration just like function declaration ?so where is it defined..is it the instance that was created? 2)---if you see the first few lines of code, Grass = function() { return this; }; there is no var mentioned,how is possible that its not showing any error as there is no var grass=0; defined prior to this?and if I am not wrong that is an object 3)---when to use this? –  May 31 '13 at 07:27
  • @AaditMShah: var g= new Grass(); is g a constructor in this? –  May 31 '13 at 07:48
  • @jayeshjain Constructors are functions which create objects. The example you cited has only two constructors - `Grass` and `Garden`. In JavaScript any function can be used as a constructor by adding `new` before the function call. Hence `var g = new Grass` calls the function `Grass` as a constructor and returns an object which is stored in `g`. This object `g` inherits all the properties of `Grass.prototype` which is the prototype of `g`. The `initialize` function is a property of the prototype and is hence inherited. It's not a constructor. Read this: http://stackoverflow.com/a/8096017/783743 – Aadit M Shah May 31 '13 at 10:37
  • @AaditMShah:and suppose if i dont wanna use constructor,and using only prototype,would it be possible to create instances and inherit the properties? i guess there create.object would come in to play? –  May 31 '13 at 11:28
  • @jayeshjain - Yes, indeed. That is the way I prefer creating objects. Say I have an object for a circle as follows: `var circle = { radius: 5, area: function () { return Math.PI * this.radius * this.radius; } };`. Now I can use `circle.area()` to calculate the area of the circle. However if I want to create another circle I just need to extend this circle. We can use a function for this: `function createCircle(radius) { var newCircle = Object.create(circle); newCircle.radius = radius; return newCircle; }`. Now I can create as many circles as I want like this: `var ball = createCirlce(10);`. =) – Aadit M Shah May 31 '13 at 11:36
  • @AaditMShah:Duniya Gol hai buddy!!!thx a ton man,but dont mind if i trouble u some more times!!! –  May 31 '13 at 11:51
  • @AaditMShah:why is the constructor grass enclosed in (function() {-----if u see it right at the beginning –  May 31 '13 at 12:02
  • @AaditMShah:right or wrong!!! grass.prototype={a:1,b:2} is basically constructor.prototype={a:1,b:2} –  May 31 '13 at 12:08
  • @jayeshjain - The constructor is enclosed in what's called an IIFE - an [immediately invoked function expression](http://benalman.com/news/2010/11/immediately-invoked-function-expression/ "Ben Alman » Immediately-Invoked Function Expression (IIFE)"). It' used to encapsulate private state. Yes, `Grass` (with a capital G) is a constructor and every function has a prototype. Hence `Grass.prototype` is kind of like `constructor.prototype`. Note however that you could also have another function called `constructor`. – Aadit M Shah Jun 01 '13 at 02:06
0

I guess I am too late, but here would be my 2 cents:

Prototype:

String.prototype.x = "yahoo"

now every instance of String will have the property x.

So be it (new String()).x or "".x both have the value equal to yahoo

Hence it's like extending a predefined class.


Objects

Everything in JavaScript, except the other primitive types, is an object.

An object is a collection of name-value pairs, nothing more, nothing less.

{"a": 0, "b" : 1}

Even an Array is an object in JS with some additional properties & methods.


Functions & Methods

Here is a function :

function a() { };

Now let's give it the status of a method of an Array:

Array.prototype.a = a;

Constructor:

new String()

gets the implementation of String from : String.constructor

Similarly the code you write in any function goes into this very function.

loxxy
  • 12,990
  • 2
  • 25
  • 56
  • *"gets the implementation of `String` from : `String.constructor`"* No, it doesn't, it gets it from `String` and `String.prototype`. Also, I would **strongly** recommend not using extending native types as your example for how prototypes work. – T.J. Crowder May 30 '13 at 12:56
  • @loxxy:dont underestimate your self,your expalnation is definately more than 2 cents,nice,short and simple!!! –  May 30 '13 at 14:08
-4

JavaScript is the scripting language used in web applications to make the web pages dynamic. This language allows to handle user actions by handling events on the elements displayed on the page.... Also it is used to modify the content on the web page based on the condition...

The method (or) function is the programming construct used in javascript for specifying the logic. You will put the your required logic in a method and you will invoke it from the web page upon any event...

There are no constructors in javascript...

There will be implicit and user defined objects in javascript... Implicit objects include Date, Array etc...

This is just a basic abstract.. you need to follow either websites (or) books to know much more about javascript

Matt Browne
  • 12,169
  • 4
  • 59
  • 75
Pavan Kumar K
  • 1,360
  • 9
  • 11