这是我在*上的第一篇文章.多年来,这个社区为我提供了许多不同编码问题的深刻见解.因此,由于我在JS中从事这项特定任务已经好几天了,所以我决定依靠这个强大的社区,看看我能在我的问题上得到什么样的帮助.
我在这里看到了一个非常不错的帖子,实际上接近我想要的帖子(post here),但是不幸的是,我需要在名称空间中创建一个Object的多个实例,该示例无济于事.
这是我正在尝试做的事情:
if (!myNamespace) {
var myNamespace = {};
}
// Object for my namesapce
myNamespace.Item = function() {
return {
Initialize: function(title,details) {
// setting members of this Object
this.title = title;
this.details = details;
},
Display: function() {
this.Position();
this.Show();
},
Position: function() {
// position my item in the DOM
},
Show: function() {
// show my item in the DOM
}
};
}();
// another Object for my namesapce
myNamespace.Basket = function() {
return {
Initialize: function(title,details,code) {
// setting members of this Object
this.items = [];
},
Add: function(item) {
this.items[items.length] = item;
}
};
}();
var Item = new myNamespace.Item; // the code fails to create a new instance of this Object
Item.Initialize("New Item Title","New Item Desc.");
Item.Display();
var Item2 = new myNamespace.Item; // the code fails to create a new instance of this Object
Item2.Initialize("New Item Title2","New Item Desc. 2");
Item2.Display();
我敢肯定,我想错了Singleton vs. Class.一个带有正确嵌套/结构的好代码示例将大有帮助!提前致谢!
解决方法:
问题在于myNamespace.Item不是函数,而是对象,因为您具有立即执行的函数.
例如,您可以将方法添加到当前对象:
myNamespace.Item = function() {
this.initialize = function(title,details,code) {
// setting members of this Object
this.title = title;
this.details = details;
this.code = code;
};
this.display = function() {
this.Position();
this.Show();
};
this.position = function() {
// position my item in the DOM
};
this.show = function() {
// show my item in the DOM
}
};
或使用构造函数的prototype属性,使使用new运算符创建的对象实例继承这些方法:
// Object for my namesapce
myNamespace.Item = function() {
// constructor logic
};
myNamespace.Item.prototype.initialize = function(title,details,code) {
// setting members of this Object
this.title = title;
this.details = details;
this.code = code;
};
myNamespace.Item.prototype.display = function() {
this.Position();
this.Show();
};
myNamespace.Item.prototype.position = function() {
// position my item in the DOM
};
myNamespace.Item.prototype.show = function() {
// show my item in the DOM
};
或更短的语法:
myNamespace.Item = function() { };
myNamespace.Item.prototype = {
initialize: function(title,details,code) {
// setting members of this Object
this.title = title;
this.details = details;
this.code = code;
},
display: function() {
this.Position();
this.Show();
},
position: function() {
// position my item in the DOM
},
show: function() {
// show my item in the DOM
},
constructor: myNamespace.Item // fix the constructor property
};
使用prototype属性的好处在于,这些方法仅存在于myNamespace.Item.prototype对象中,而在第一个示例中,每个对象都有其自己的函数实例,这些实例的内存效率较低.