gpt4 book ai didi

Javascript 面向对象的应用结构

转载 作者:行者123 更新时间:2023-11-29 19:38:27 24 4
gpt4 key购买 nike

我正在尝试以更加面向对象的方式重写 JS 网络应用程序。

假设我有一个名为 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com