第一种
var a = {};
uniqueId = (function(){
var id = 0;
return function(){
return id++;
}
})()
alert(a.uniqueId());
alert(a.uniqueId());
alert(a.uniqueId());
alert(a.uniqueId());
第二种
var a = {};
a.uniqueId = function(){
var id = 0;
return function(){
id++;
return id
}();
}
alert(a.uniqueId());
alert(a.uniqueId());
alert(a.uniqueId());
alert(a.uniqueId());
闭包的差异能够说清楚么?
var a = {};
uniqueId = (function(){
var id = 0;
return function(){
return id++;
}
})()
alert(a.uniqueId());
alert(a.uniqueId());
alert(a.uniqueId());
alert(a.uniqueId());
第二种
var a = {};
a.uniqueId = function(){
var id = 0;
return function(){
id++;
return id
}();
}
alert(a.uniqueId());
alert(a.uniqueId());
alert(a.uniqueId());
alert(a.uniqueId());
闭包的差异能够说清楚么?
本文通过两种不同的JavaScript实现方式,展示了如何利用闭包来创建唯一的ID。第一种方法使用立即执行函数表达式(IIFE),第二种方法则是在对象内部定义函数。这两种方式都能确保每次调用时返回一个新的递增ID。
1013

被折叠的 条评论
为什么被折叠?



