什么是创建 JavaScript 类的适当、现代和跨浏览器安全的方法

What is a proper, modern and cross-browser safe method of creating JavaScript classes?

本文关键字:浏览器 方法 安全 创建 JavaScript 什么      更新时间:2023-09-26

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

我认为这应该很容易,并且不需要框架来用语言创建类 - 也许我错过了一些东西。

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

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

如果能提供一个正确构造类的例子,我会很感激,只有几句话的解释。

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

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

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

我认为你可以考虑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;
})();

如果你有信心使用CoffeeScript,它有可靠的类方法,并且与任何其他OOP框架相比,它提供了更清晰的语法。