在 javascript 中实现 OOP 的更好方法
我想用 JavaScript 和 Canvas 做一个框架(学术上)动画,我开始寻找使用 JavaScript 进行面向对象编程的指南,我发现了太多的变化。
示例:
// Example 1
var object = {
public_method: function(){ //do something }
}
// Example 2
function object(){
this.public_method = function(){ //do something }
}
var o = new object();
这是正确或最好的方法(简单且轻松)。
注意:对于此类项目有什么好的设计模式吗?
I want to do a framework (academically) animations in JavaScript and Canvas, I began to look for guides DONE of object-oriented programming with javascript and I find too many variations.
examples:
// Example 1
var object = {
public_method: function(){ //do something }
}
// Example 2
function object(){
this.public_method = function(){ //do something }
}
var o = new object();
which is the correct or best way (simple and light) to do so.
note: that good design pattern for this kind of project?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第一个只会创建一个实例,而第二个可用于创建多个实例。
我更喜欢使用构造函数并将方法放在原型中。这样,方法就会为所有实例创建一次,而不是为每个实例单独创建:
The first will only create one single instance, while the second can be used to create several instances.
I prefer using a constructor function and putting the methods in the prototype. That way the methods are created once for all instances instead of created separately for each instance:
如果您想要类似于经典 OOP 设计(围绕类)的东西,您应该这样做:
我建议您阅读有关
原型
的更多内容。这使您能够创建同一“类”的许多实例,而无需浪费内存、执行和编程来分别为每个实例定义方法。If you want something that will be similar to the classic OOP design (which revolves around classes), you should do something like this:
I suggest you read more about
prototype
. This enables you creating many instances of the same "class", without wasting memory, execution and programming defining the methods for each instance separately.