var obj={};
['width','height'].forEach(function(item,index){
obj[item]=function(){
console.log(item);
}
});
console.log(obj.width==obj.height);
控制台打印false,说明obj.width和obj.height不是一个函数副本,一样的代码块,内存中有两个内存副本,js为什么没有做内存优化呢?
更为奇怪的是,这种写法是zepto.js中大量使用的写法,例如:
['width', 'height'].forEach(function (dimension) {
var dimensionProperty =
dimension.replace(/./, function (m) {
return m[0].toUpperCase()
})
$.fn[dimension] = function (value) {
var offset, el = this[0]
if (value === undefined) return isWindow(el) ? el['inner' + dimensionProperty] :
isDocument(el) ? el.documentElement['scroll' + dimensionProperty] :
(offset = this.offset()) && offset[dimension]
else return this.each(function (idx) {
el = $(this)
el.css(dimension, funcArg(this, value, idx, el[dimension]()))
})
}
})
是这种写法有问题,会造成同样的代码块生成不同副本占用过多内存资源,还是我分析出了问题呢?来个高手帮我分析下吧。
函数不只有代码,还有其所处的环境,二者构成一个不可分割的整体