我正在尝试以更面向对象的方式重写 JS Web 应用程序。
假设我有一个名为 Application 的主对象:
var Application = (function(obj) {
obj.init = function() {
console.log("Application init");
};
obj.move = function() {
return {
left: function() { console.log("Move left"); },
right: function() { console.log("Move right"); }
}
}
return obj;
})(Application || {});
我想添加另一个可能有多个实例的方法,因此我需要添加一个原型(prototype):(这发生在另一个文件中)
var Application = (function(obj) {
obj.child = function() {
return {
typeA: function() {
console.log("New child object of type A");
this.childID = Math.floor((Math.random() * 10) + 1); // Just a random number
},
typeB: function() {
console.log("New child object of type B");
this.childID = Math.floor((Math.random() * 10) + 1); // Just a random number
}
}
// This is where it goes wrong
obj.child.typeA.prototype = function() {
getID: function() { console.log(this.childID) }
}
};
return obj;
})(Application || {});
我的问题是我无法访问 typeA()
的原型(prototype)函数 getID
。
这可能是因为我构建应用程序的方式。
我希望能够像这样调用原型(prototype)方法:
var a = Application.child.typeA();
a.getID();
如何以正确的方式为这样的对象添加原型(prototype)?
我是面向对象的 Javascript 新手,并且由于有很多方法可以在 JS 中构建面向对象的应用程序,所以我很确定我把它们搞砸了。
最佳答案
What am I doing wrong here?
child
是一个返回对象的函数,您似乎想让它成为对象本身。此外,它确实在原型(prototype)分配完成之前返回
。原型(prototype)“对象”本身是对象文字和函数之间的语法混合。
相反,使用
var Application = (function(obj) {
obj.child = {
typeA: function() {
console.log("New child object of type A");
this.childID = Math.floor((Math.random() * 10) + 1); // Just a random number
},
typeB: function() {
console.log("New child object of type B");
this.childID = Math.floor((Math.random() * 10) + 1); // Just a random number
}
};
obj.child.typeA.prototype.getID = function() {
console.log(this.childID)
};
return obj;
})(Application || {});
您也可以直接将对象文字分配给 .prototype
,但是 that is not recommended过度修改现有对象。
Is the way I am structuring my application a good practice?
是的,这是一种常见的模式。
关于Javascript面向对象的应用程序结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24429924/