• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

javascript - Why use a closure instead of a prototype?

Sgraffite

Senior member
I see this all the time, but I've never understand the reason other than maybe habit? That's my only guess.

For example:
Code:
function Foo() {
	var temp = 1;
	function bar() {
		console.log(temp);
	}
	function barPlusOne() {
		console.log(temp + 1);
	}
}

Code:
Foo.prototype = {
	temp: 1,
	bar: function(){
		console.log(this.temp);
	},
	barPlusOne: function() {
		console.log(this.temp + 1);
	}
}

I could definitely be missing something, but I've always written it the latter way.
 
I meant the use of closures for encapsulating data structures instead of using object prototypes to do so. Anonymous functions for callbacks aren't really closures as far as I am aware.
 
I meant the use of closures for encapsulating data structures instead of using object prototypes to do so. Anonymous functions for callbacks aren't really closures as far as I am aware.

They are

https://en.wikipedia.org/wiki/Closure_(computer_programming)

Pretty much the only two requirements for something to be a closure are that it must be passable and it must include current scope at its declaration.

Pretty much every function in javascript, anonymous or otherwise, is a closure because of the javascript scope rules.
 
Back
Top