4

我对数百种创建 JS 类的方法感到困惑。有人说我应该使用原型,而另一些人说没有人使用原型,因为它“不好”。另一方面,CoffeeScript 使用原型,但用函数 whick 返回自身(或其他东西)包装了一个构造。我见过返回对象的函数,返回返回对象的函数的函数等。

我认为这应该很容易,并且不需要任何框架来创建一种语言的类——也许我遗漏了一些东西。

还有两种(至少)创建方法的方法:foo: function() {}function foo() {}。我什至在单节课上见过这两种方式。问题是第一种方法会导致创建匿名函数(恰好被分配给对象的字段)并且调试器说错误发生在由匿名函数等调用的匿名函数中。

我知道 JS 旨在实现功能而不是 OOP,但有时类是描述概念的最佳方式(例如,UI 小部件想要成为类)。

我会很感激一个正确构建类的例子,几乎没有解释。

4

3 回答 3

3

我认为您可以考虑 CoffeeScript 产生“好”的代码:

// Create a "class" named Foo = create a variable that contains whatever the
// self-invoking anonymous function returns (the function avoids the pollution
// the global namespace).
var Foo = (function() {

  // Create the "class" = the constructor function that is supposed to be used
  // with the "new" keyword to create instances (objects).
  function Foo() {}

  // Add a method "bar" (that's what the prototype is for!)
  Foo.prototype.bar = function(baz) {
    // Assign the value to a member variable of the current instance (this)
    this.foobar = baz;
  };

  // ...add more stuff.

  // Return only the function, every other local variable stays in this scope.
  return Foo;

})();
于 2012-08-08T09:03:18.550 回答
3

我认为这篇文章解释得很好:

https://developer.mozilla.org/en-US/docs/JavaScript/Introduction_to_Object-Oriented_JavaScript

这是(我相信)在基于原型的语言(如 javascript)中使用类的正确方法,并很好地解释了这些概念。我在我的项目中使用这种方法,它似乎适用于所有现代浏览器。

于 2012-08-08T09:17:03.600 回答
0

如果您对使用 CoffeeScript 有信心,那么与任何其他 OOP 框架相比,它具有可靠的类方法,并为您提供更清晰的语法。

于 2012-08-08T08:54:28.190 回答