簡體   English   中英

我們在JavaScript中關閉和原型之間的區別是什么?

[英]What us the difference between closure and prototyping in JavaScript?

我正在檢查JavaScript的閉包和原型 我編寫了兩個基本的HTML返回函數 ,基本上它們都返回相同的輸出。 它們兩者之間是否有任何區別/關系,為什么我們應該使用閉包?

 //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')); 

每次使用閉包創建對象時,都會有它們的方法的副本(它們在內存中作為Function類型的獨立對象,即使它們執行相同的操作)。 如果使用原型方法,則無論創建多少個對象,其每個方法(一個原型)都將只有一個副本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM