我正在通过 Javascript 构建一个很大程度上基于浏览器的 Web 应用程序。
当我需要一个位于单独文件中的模块时,我不知道这三种方法中哪一种对于 javascript 引擎占用的内存是最好的:
思路一,在extend方法中赋值变量
function (ContactCollection , ItemCollection, ContactListView) {
var ContactExample = function (inst) {
// Wild examples of possible uses :
this.collections.contact.each(function(model) {
// do something with each model
});
this.collections.item.on('reset', this.resetItems, this);
this.$el.remove().append(this.view.render().el);
};
jQuery.extend(true, ContactExample.prototype, {
'collections': {
'contact': ContactCollection,
'item': ItemCollection
},
'view': ContactListView,
'$el': jQuery('#somediv'),
}, ContactExample);
return new ContactExample();
};
思路2,在实例化方法中赋值变量:
function (ContactCollection , ItemCollection, ContactListView) {
var ContactExample = function (inst) {
// Wild examples of possible uses :
inst.collections.contact.each(function(model) {
// do something with each model
});
inst.collections.item.on('reset', this.resetItems, this);
inst.$el.remove().append(this.view.render().el);
}
jQuery.extend(true, ContactExample.prototype, {
'$el': jQuery('#somediv')
}, ContactExample);
return new ContactExample({
'collections': {
'contact': ContactCollection,
'item': ItemCollection
},
'view': ContactListView
});
};
想法3,只需在代码中使用它们,因为它们已经在函数范围内被引用:
function (ContactCollection , ItemCollection, ContactListView) {
var ContactExample = function (inst) {
// Wild examples of possible uses :
ContactCollection.each(function(model) {
// do something with each model
});
ItemCollection.on('reset', this.resetItems, this);
this.$el.remove().append(ContactListView.render().el);
}
});
jQuery.extend(true, ContactExample.prototype, {
'$el': jQuery('#somediv')
}, ContactExample);
return new ContactExample();
});
什么(以及为什么)是在 javascript 内存引擎中处理变量的最佳方式。
谢谢您的回答