3 ways to define a JavaScript class

3 ways to define a JavaScript class

September 29th, 2006. Tagged: JavaScript

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.

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.

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.

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:

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

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:

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. 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.

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.

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:

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.

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() {
时间: 2024-10-10 15:08:10

3 ways to define a JavaScript class的相关文章

【译】3 ways to define a JavaScript class

本文真没啥难点,我就是为了检验我英语水平退化了没哈哈虽然我英语本来就渣翻译起来也像大白话.将原文看了一遍也码完翻译了一遍差不多一个小时,其中批注部分是自己的理解如有疏漏或误解还请之处感激不尽呐,比如JavaScript中对于单例的理解感觉定义有些模糊啊. 翻译自斯托扬·斯蒂凡诺夫的原文链接:http://www.phpied.com/3-ways-to-define-a-javascript-class/ 引言 当涉及到语法时JavaScript是一个非常灵活的面向对象语言.这篇文章你可以找到三

[Python Cookbook] Pandas: 3 Ways to define a DataFrame

Using Series (Row-Wise) import pandas as pd purchase_1 = pd.Series({'Name': 'Chris', 'Item Purchased': 'Dog Food', 'Cost': 22.50}) purchase_2 = pd.Series({'Name': 'Kevyn', 'Item Purchased': 'Kitty Litter', 'Cost': 2.50}) purchase_3 = pd.Series({'Name

[转]大型 JavaScript 应用架构中的模式

目录 1.我是谁,以及我为什么写这个主题 2.可以用140个字概述这篇文章吗? 3.究竟什么是“大型”JavaScript应用程序? 4.让我们回顾一下当前的架构 5.想得长远一些 6.头脑风暴 7.架构提议 7.1 模块化理论 7.2 CommonJS模块 7.3 外观模式 7.4 中介者模式 7.5 应用外观 7.6 核心的抽象 7.7 整合 7.8 超越发布/订阅:自动注册事件 7.9 常见问题 13 August 2013 原文:Patterns For Large-Scale Java

JavaScript Modules

One of the first challenges developers new to JavaScript who are building large applications will have to face is how to go about organizing their code. Most start by embedding hundreds of lines of code between a <script> tag which works but quickly

Top 10 JavaScript traps for a C# developer

Top 10 JavaScript traps for a C# developer 27 May 2014   | .NET · Code · Javascript Tags: .net · C# · javascript If you are an experienced C# developer, coming into JavaScript world for application development, you will end up making few common mista

Native JavaScript Development after Internet Explorer

This article has nothing to do with the decision whether or not to abandon support for oldIE. You and you alone must take that decision based on the specific details of your website or application. With all this being said, let us proceed! 1. JavaScr

Learning JavaScript Design Patterns -- A book by Addy Osmani

Learning JavaScript Design Patterns A book by Addy Osmani Volume 1.6.2 Tweet Copyright © Addy Osmani 2015. Learning JavaScript Design Patterns is released under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 unported license. It

Top JavaScript Frameworks, Libraries &amp; Tools and When to Use Them

It seems almost every other week there is a new JavaScript library taking the web community by storm! The web community is increasingly vibrant, diverse and is moving rapidly on multiple fronts. It would be an impossible feat to survey every major Ja

5种你未必知道的JavaScript和CSS交互的方法

我们的网页中都有.js文件和.css文件,但这并不意味着CSS和js是独立不能交互的.下面要讲的这五种JavaScript和CSS共同合作的方法你也许未必知道!随着浏览器不断的升级改进,CSS和JavaScript之间的界限越来越模糊.本来它们是负责着完全不同的功能,但最终,它们都属于网页前端技术,它们需要相互密切的合作.我们的网页中都有.js文件和.css文件,但这并不意味着CSS和js是独立不能交互的.下面要讲的这五种JavaScript和CSS共同合作的方法你也许未必知道!用JavaScr