定义JavaScript类的3种方法

介绍(Introduction)

JavaScript is a very flexible object-oriented language when it comes to syntax. In this article you can find three ways of defining and instantiating an object. Even if you have already picked your favorite way of doing it, it helps to know some alternatives in order to read other people's code.

就语法而言,JavaScript是一种非常灵活的面向对象语言。 在本文中,您可以找到三种定义和实例化对象的方法。 即使您已经选择了自己喜欢的方式,也有助于了解一些替代方法,以便阅读他人的代码。

It's important to note that there are no classes in JavaScript. Functions can be used to somewhat simulate classes, but in general JavaScript is a class-less language. Everything is an object. And when it comes to inheritance, objects inherit from objects, not classes from classes as in the "class"-ical languages.

重要的是要注意,JavaScript中没有类。 函数可以用来在某种程度上模拟类,但是通常JavaScript是一种无类语言。 一切都是对象。 当涉及到继承时,对象是从对象继承的,而不是像“类”语言那样从类继承的类。

1.使用功能 (1. Using a function)

This is probably one of the most common ways. You define a normal JavaScript function and then create an object by using the new keyword. To define properties and methods for an object created using function(), you use the this keyword, as seen in the following example.

这可能是最常见的方法之一。 您定义一个普通JavaScript函数,然后使用new关键字创建一个对象。 要为使用function()创建的对象定义属性和方法,请使用this关键字,如以下示例所示。

function Apple (type) {
    this.type = type;
    this.color = "red";
    this.getInfo = getAppleInfo;
}
 
// anti-pattern! keep reading...
function getAppleInfo() {
    return this.color + ' ' + this.type + ' apple';
}

To instantiate an object using the Apple constructor function, set some properties and call methods you can do the following:

要使用Apple构造函数实例化对象,设置一些属性和调用方法,您可以执行以下操作:

var apple = new Apple('macintosh');
apple.color = "reddish";
alert(apple.getInfo());

1.1。 内部定义的方法 (1.1. Methods defined internally)

In the example above you see that the method getInfo() of the Apple "class" was defined in a separate function getAppleInfo(). While this works fine, it has one drawback – you may end up defining a lot of these functions and they are all in the "global namespece". This means you may have naming conflicts if you (or another library you are using) decide to create another function with the same name. The way to prevent pollution of the global namespace, you can define your methods within the constructor function, like this:

在上面的示例中,您看到Apple“类”的方法getInfo()是在单独的函数getAppleInfo()中定义的。 尽管这很好用,但它有一个缺点–您可能最终定义了许多这样的函数,而且它们都在“全局名称规范”中。 这意味着,如果您(或正在使用的另一个库)决定创建具有相同名称的另一个函数,则可能会导致命名冲突。 防止污染全局名称空间的方法是,可以在构造函数中定义方法,如下所示:

function Apple (type) {
    this.type = type;
    this.color = "red";
    this.getInfo = function() {
        return this.color + ' ' + this.type + ' apple';
    };
}

Using this syntax changes nothing in the way you instantiate the object and use its properties and methods.

使用此语法,在实例化对象以及使用其属性和方法方面没有任何改变。

1.2。 添加到原型的方法 (1.2. Methods added to the prototype)

A drawback of 1.1. is that the method getInfo() is recreated every time you create a new object. Sometimes that may be what you want, but it's rare. A more inexpensive way is to add getInfo() to the prototype of the constructor function.

1.1的缺点。 是每次创建新对象时都会重新创建方法getInfo()。 有时这可能就是您想要的,但这很少见。 一种更便宜的方法是将getInfo()添加到构造函数的原型中。

function Apple (type) {
    this.type = type;
    this.color = "red";
}
 
Apple.prototype.getInfo = function() {
    return this.color + ' ' + this.type + ' apple';
};

Again, you can use the new objects exactly the same way as in 1. and 1.1.

同样,您可以使用与1.和1.1中完全相同的方式使用新对象。

2.使用对象文字 (2. Using object literals)

Literals are shorter way to define objects and arrays in JavaScript. To create an empty object using you can do: var o = {}; instead of the "normal" way: var o = new Object(); For arrays you can do: var a = []; instead of: var a = new Array(); So you can skip the class-like stuff and create an instance (object) immediately. Here's the same functionality as described in the previous examples, but using object literal syntax this time:

文字是在JavaScript中定义对象和数组的较短方法。 要使用创建空对象,您可以执行以下操作: var o = {}; 而不是“常规”方式: var o = new Object(); 对于数组,您可以执行以下操作: var a = []; 而不是: var a = new Array(); 因此,您可以跳过类之类的内容,并立即创建一个实例(对象)。 这与前面的示例中描述的功能相同,但是这次使用对象文字语法:

var apple = {
    type: "macintosh",
    color: "red",
    getInfo: function () {
        return this.color + ' ' + this.type + ' apple';
    }
}

In this case you don't need to (and cannot) create an instance of the class, it already exists. So you simply start using this instance.

在这种情况下,您不需要(也不能)创建该类的实例,因为它已经存在。 因此,您只需开始使用此实例。

apple.color = "reddish";
alert(apple.getInfo());

Such an object is also sometimes called singleton. In "classical" languages such as Java, singleton means that you can have only one single instance of this class at any time, you cannot create more objects of the same class. In JavaScript (no classes, remember?) this concept makes no sense anymore since all objects are singletons to begin with.

这样的对象有时也称为单例。 在Java之类的“经典”语言中,单例意味着您在任何时候都只能拥有该类的一个实例,不能创建更多相同类的对象。 在JavaScript中(没有类,还记得吗?),这个概念不再有意义,因为所有对象都是以单例开头的。

3.使用功能的单例 (3. Singleton using a function)

Again with the singleton, eh? 🙂

再次与单身人士,是吗? 🙂

The third way presented in this article is a combination of the other two you already saw. You can use a function to define a singleton object. Here's the syntax:

本文介绍的第三种方法是您已经看到的其他两种方法的组合。 您可以使用函数来定义单例对象。 语法如下:

var apple = new function() {
    this.type = "macintosh";
    this.color = "red";
    this.getInfo = function () {
        return this.color + ' ' + this.type + ' apple';
    };
}

So you see that this is very similar to 1.1. discussed above, but the way to use the object is exactly like in 2.

因此,您将看到它与1.1非常相似。 上面已经讨论过了,但是使用对象的方式与第2部分完全相同。

apple.color = "reddish";
alert(apple.getInfo());

new function(){...} does two things at the same time: define a function (an anonymous constructor function) and invoke it with new. It might look a bit confusing if you're not used to it and it's not too common, but hey, it's an option, when you really want a constructor function that you'll use only once and there's no sense of giving it a name.

new function(){...}执行两件事:定义一个函数(一个匿名构造函数)并使用new调用它。 如果您不习惯它并且不太常见,那么它可能看起来有点令人困惑,但是,嘿,这是一个选择,当您真的想要一个构造函数仅使用一次并且没有名称的感觉时。

概要 (Summary)

You saw three (plus one) ways of creating objects in JavaScript. Remember that (despite the article's title) there's no such thing as a class in JavaScript. Looking forward to start coding using the new knowledge? Happy JavaScript-ing!

您看到了用JavaScript创建对象的三种(加一)方式。 请记住,尽管有文章标题,但JavaScript中没有类。 期待开始使用新知识进行编码吗? JavaScript快乐!

Tell your friends about this post on Facebook and Twitter

FacebookTwitter上告诉您的朋友有关此帖子的信息

翻译自: https://www.phpied.com/3-ways-to-define-a-javascript-class/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值