可以使用哪些技术在 JavaScript 中定义类,它们的权衡是什么? [英] What techniques can be used to define a class in JavaScript, and what are their trade-offs?

查看:17
本文介绍了可以使用哪些技术在 JavaScript 中定义类,它们的权衡是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我更喜欢在大型项目中使用 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 进行面向对象编程,第一部分:继承 -Doc 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 使用基于 prototype 的继承方案.

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 中的类功能.您至少需要查看 PrototypejQuery.

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.

决定哪一个是最好的"是在 StackOverflow 上开始一场圣战的好方法.如果您正在着手一个更大的 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆