alaska
alaska

Reputation: 151

the difference between object with constructor and closure in javascript

I am new to JavaScript, and I am now confused by the two conceptions: object with constructor and prototype, and closure.

Here, closure means function with other functions nested in it, and its environment.

I feel that these two conceptions seems to be similar from a certain point of view:

they both have variables, which is like fields in other languages. In closure, it is called environment, which I think is a kind of binding between values and certain variables.

Moreover, they both have "methods". In closure, I think the inner nested functions act just like this.

So, what is the essential difference between these two conceptions? Or, how the two approaches to remembering data differ?

If I made some errors in these conceptions above, please correct me, thank you.

Upvotes: 2

Views: 926

Answers (2)

Tejs
Tejs

Reputation: 41246

Closures and prototypes really aren't the same thing.

The prototype is the template upon which the new object is created (in a nutshell); so for example:

 var someType = function()
 {
 };

 someType.prototype.someOtherFunction = function()
 {
 };

Whenever you create an instance of sometype, it will have a someOtherFunction member attached that is a function. In addition, other instances pickup the value. So it's easy to "add" functions to string for example:

String.prototype.doSomething = function() 
{

}

And now all strings get this method.

Closures are really a subscope inside another scope, and it's the act of capturing or closing around a variable from the outer scope into the inner scope that makes it a closure.

So for example:

function something()
{
    for(var j = 0; j < 10; j++)
    {
        setTimeout(function()
        {
            alert(j);
        }, 25);
    }
}

In this situation, the value of j is closed around by the setTimeout callback. In any other context, j wouldn't exist inside the inner function (since it's neither a global nor argument to the function), but because it has been introduced in this way, the inner function is said to close over the variable reference.

Upvotes: 0

Graham
Graham

Reputation: 6562

Well, a closure doesn't have 'methods' as such, as it isn't really a concrete object - its more of a concept. Closures are implimented using functions, and functions themselves can have methods, but you wouldn't describe a closure as having methods. As you say, a closure is a function plus information about its environment.

On the other hand a prototype is just a basic JavaScript object, so its correct to say that a prototype has methods.

Upvotes: 3

Related Questions