定义JavaScript类的3种方法

news/2024/7/19 14:32:45 标签: java, python, javascript, js, css

介绍(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

在Facebook和Twitter上告诉您的朋友有关此帖子的信息

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


http://www.niftyadmin.cn/n/1306976.html

相关文章

FusionCharts MSBar3D图

1、静态页面 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><title>FusionCharts MSBar3D图</title><meta http-equiv"keywords" content"keyword1,keyword2,keyword3">&l…

Python多进程(一)进程及进程池

进程 进程是操作系统分配资源的基本单元&#xff0c;是程序隔离的边界。 进程和程序 程序只是一组指令的集合&#xff0c;它本身没有任何运行的含义&#xff0c;它是静态的。进程程序的执行实例&#xff0c;是动态的&#xff0c;有自己的生命周期&#xff0c;有创建有撤销&a…

dojo表格的一些属性

dojo表格的属性总结归纳 1、表格无数据提示 data-dojo-props"noDataMessage:无数据..." 2、表格的高度自动适应 autoHeight"true"

javascript 书_JavaScript书就快到了

javascript 书Whew, after a whole year of writing, preparation, edits, blood, sweat, tears, I finished all the latest edits and reviews for my new book, Beginning Object-Oriented JavaScript. It should be out any day now. I cant be happier! 经过一整年的编写&…

Python多进程(二)之进程同步及通信

上篇文章介绍了什么是进程、进程与程序的关系、进程的创建与使用、创建进程池等&#xff0c;接下来就来介绍一下进程同步及进程通信。 进程同步 当多个进程使用同一份数据资源的时候&#xff0c;因为进程的运行没有顺序&#xff0c;运行起来也无法控制&#xff0c;如果不加以…

Python多线程讲解

线程 线程&#xff08;Thread&#xff09;&#xff0c;有时也被称为轻量级进程(Lightweight Process&#xff0c;LWP&#xff09;&#xff0c;是操作系统独⽴调度和分派的基本单位&#xff0c;本质上就是一串指令的集合。 ⼀个标准的线程由线程id、当前指令指针(PC&#xff09…

FusionCharts中图的属性的总结归纳

FusionCharts中图的属性的总结归纳 1、横坐标label间隔显示 labelStep"4" 2、柱状图有椭圆角 useRoundEdges"1"

Anaconda豪华轿车:吉他零件

Im part of a band that has an album out now. I know, right? (links: excuse-for-a-site, amazon, itunes). 我是现在有专辑的乐队的一部分。 我知道&#xff0c;对吧&#xff1f; (链接&#xff1a;网站的借口&#xff0c;亚马逊和iTunes )。 I wanted to put up all the …