在 javascript 中实现 OOP 的更好方法

发布于 2024-12-12 03:13:59 字数 364 浏览 0 评论 0原文

我想用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

殤城〤 2024-12-19 03:13:59

第一个只会创建一个实例,而第二个可用于创建多个实例。

我更喜欢使用构造函数并将方法放在原型中。这样,方法就会为所有实例创建一次,而不是为每个实例单独创建:

function ExampleObject() {
  this.answer = 42;
}

ExampleObject.prototype = {
  get_answer: function(){ return this.answer; },
  another_method: function(){}
};

var obj = new ExampleObject();
alert(obj.get_answer());

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:

function ExampleObject() {
  this.answer = 42;
}

ExampleObject.prototype = {
  get_answer: function(){ return this.answer; },
  another_method: function(){}
};

var obj = new ExampleObject();
alert(obj.get_answer());
故事灯 2024-12-19 03:13:59

如果您想要类似于经典 OOP 设计(围绕)的东西,您应该这样做:

function MyClass(param1, param2) {
    this.param1 = param1;
    this.param2 = param2; // These are fields.
}
MyClass.prototype.publicMethod = function() {
    // do something
}
var o = new MyClass(x, y);

我建议您阅读有关原型的更多内容。这使您能够创建同一“类”的许多实例,而无需浪费内存、执行和编程来分别为每个实例定义方法。

If you want something that will be similar to the classic OOP design (which revolves around classes), you should do something like this:

function MyClass(param1, param2) {
    this.param1 = param1;
    this.param2 = param2; // These are fields.
}
MyClass.prototype.publicMethod = function() {
    // do something
}
var o = new MyClass(x, y);

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文