在JavaScript中可以使用什么技术来定义类,它们的权衡是什么? [英] What techniques can be used to define a class in JavaScript, and what are their trade-offs?
问题描述
我喜欢在大型项目中使用OOP,像我现在工作的项目。我需要在JavaScript中创建几个类,但是,如果我没有误解,至少有几种方法去做。将是什么语法,为什么会这样做?
I prefer to use OOP in large scale projects like the one I'm working on right now. I need to create several classes in JavaScript but, if I'm not mistaken, there are at least a couple of ways to go about doing that. What would be the syntax and why would it be done in that way?
我想避免使用第三方库 - 至少在开始。
寻找其他答案,我发现了这篇文章 使用JavaScript的面向对象编程I:继承 - 文档JavaScript ,讨论了JavaScript中的面向对象编程。有没有更好的方法来做继承?
I would like to avoid using third-party libraries - at least at first.
Looking for other answers, I found the article Object-Oriented Programming with JavaScript, Part I: Inheritance - Doc JavaScript that discusses object-oriented programming in JavaScript. Is there a better way to do inheritance?
推荐答案
以下是不使用任何外部库的方法:
Here's the way to do it without using any external libraries:
// Define a class like this
function Person(name, gender){
// Add object properties like this
this.name = name;
this.gender = gender;
}
// Add methods like this. All Person objects will be able to invoke this
Person.prototype.speak = function(){
alert("Howdy, my name is" + this.name);
};
// Instantiate new objects with 'new'
var person = new Person("Bob", "M");
// Invoke methods like this
person.speak(); // alerts "Howdy, my name is Bob"
现在真正的答案是复杂得多比起那个来说。例如,在JavaScript中没有类这样的东西。 JavaScript使用原型
的继承方案。
Now the real answer is a whole lot more complex than that. For instance, there is no such thing as classes in JavaScript. JavaScript uses a prototype
-based inheritance scheme.
此外,还有许多流行的JavaScript库,它们有自己的风格在JavaScript中接近类似类的功能。您至少需要查看 Prototype 和 jQuery 。
In addition, there are numerous popular JavaScript libraries that have their own style of approximating class-like functionality in JavaScript. You'll want to check out at least Prototype and jQuery.
决定这些是最好的是一个伟大的方式来启动一个神圣的战争上Stack&Overflow。如果你正在开发一个更大的JavaScript重型项目,它绝对值得学习一个流行的图书馆,并按他们的方式。我是一个Prototype的家伙,但Stack Overflow似乎倾向于jQuery。
Deciding which of these is the "best" is a great way to start a holy war on Stack Overflow. If you're embarking on a larger JavaScript-heavy project, it's definitely worth learning a popular library and doing it their way. I'm a Prototype guy, but Stack Overflow seems to lean towards jQuery.
至于只有一种方法来做它,没有任何依赖外部库,我写的方式几乎是。
As far as there being only "one way to do it", without any dependencies on external libraries, the way I wrote is pretty much it.
这篇关于在JavaScript中可以使用什么技术来定义类,它们的权衡是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!