edit Уреди тему

3 ways to define a JavaScript class

Увод

JavaScript је врло флексибилан објектно-оријентисани језик кад је реч о синтакси. У овом чланку можете пронаћи три начина дефинисања и коришћења објеката. Чак и ако већ имате и користите свој омиљени начин, није згорег да се упознате са алтернативама, како би, између осталог, лакше читали код других људи. Важно је напоменути да не постоје класе у JavaScript-у. Функције се могу користити на начин да симулирају класе, али генерално JavaScript је језик без класа. Све је објекат. А када се ради о наследству, објекти насљеђују особине од објеката, а не класе од класа као у „клас“-ичним језицима.1. Коришћењем функције

=============­========= Ово је један од најчешће коришћених начина. Дефинишете нормалну JavaScript функцију, а онда креирате објекат користећи new кључну реч. За дефинисање својстава и метода за класу направљену помоћу function() користи се this кључна реч, као што се види на следећем примеру.

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

To instantiate an object of the Apple class, 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 same class, 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.

2. Using JSON

JSON stands for JavaScript Object Notation; it simply uses the short way of defining objects and arrays in JavaScript. To create an empty object using JSON 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 using the JSON you can define a class, while at the same time creating an instance (object) of that class. Such a class/object is also called „singleton“ which means that you can have only one single instance of this class at any time, you cannot create more objects of the same class. Here's the same class described in the previous examples, but using JSON 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());

3. Singleton using a function

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

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

Закључак

You saw three (plus one) ways of defining a class and instantiating an object of this class in JavaScript. Looking forward to start coding using the new knowledge? Happy JavaScript-ing!

Како бисте поставили Ваш коментар морате се учланити/пријавити на сајт.