我试图用一种更面向对象的方式重写一个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 || {});我想添加另一个可能有多个实例的方法,所以我需要添加一个原型:(这发生在另一个文件中)
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()的原型函数typeA()。这可能是因为我构建应用程序的方式。我希望能够像这样调用原型方法:
var a = Application.child.typeA();
a.getID();如何以适当的方式为这样的对象添加一个原型?
我对面向对象的Javascript很陌生,而且在JS中构建一个面向对象的应用程序的方法太多了,所以我非常肯定我会把它们搞砸。
发布于 2014-06-26 12:05:44
我在这里做错什么了?
child是一个返回对象的函数,您似乎希望使它成为对象本身。而且,它在原型任务完成之前就已经完成了return。原型" object“本身就是一个对象文字和一个函数之间的句法组合。
相反,使用
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。
我构建应用程序的方式是一个很好的实践吗?
是的,这是一种常见的模式。
https://stackoverflow.com/questions/24429924
复制相似问题