Reputation: 608
I am checking the closure and prototype in JavaScript. I write two basic HTML return functions, basically they both return the same output. Is their any difference/relation between this two and why we should use closure?
//Closure
function createLI(tags) {
return function(...args) {
if (args.length > 1) {
return args.map((iteam) => {
return "<" + tags + ">" + iteam + "</" + tags + ">"
})
} else {
return "<" + tags + ">" + args + "</" + tags + ">"
}
}
}
var tag = createLI('li');
console.log(tag('test'));
//prototype function
let Newfunction = function(x) {
this.content = x;
}
Newfunction.prototype.aswrapper = function(...args) {
if (args.length > 1) {
return args.map((iteam) => {
return "<" + this.content + ">" + iteam + "</" + this.content + ">"
})
} else {
return "<" + this.content + ">" + args + "</" + this.content + ">"
}
}
let heading = new Newfunction('h1');
heading.aswrapper('sometextprint');
console.log(heading.aswrapper('sometextprint'));
Upvotes: 0
Views: 61
Reputation: 3456
Everytime you use a closure to create an object, there's a copy of their methods (they are in memory as independent objects of type Function
, even if they do the same). If you use the prototype approach, no matter how many objects you create, there will only be a copy for each of its methods (the one of the prototype).
Upvotes: 2