-2

i've got a basic question about instancing of an object in NodeJS and different ways to declare classes. I've saw few tutorials but no tutorial has descriped, when i should use which way or why there are different ways.

I want to create a instance of an object and have created two code-snippets which does exactly the same but with a completly different code.

My question: Do i get the same result or is there something special i cannot see that it is different and moreover, which way should i use?

ExampleA:

class ExampleA {

    constructor () { }

    method() {
        console.log("Hello world");
    }
}
module.exports.ExampleA = ExampleA;

ExampleB:

function ExampleB() {
}

NoSQL1.prototype.method = function() {
    console.log("Hello world");
}
module.exports.ExampleB = ExampleB;

If i got it right, in ExampleB i just add a new function to a existing class within the "Classname.prototype.Method"

Maybe there are even more ways to go? As a C# developer i prefer the ExampleA, currently...

Kevin H.
  • 662
  • 1
  • 6
  • 16
  • Possible duplicate of [Understanding why true prototypal inheritance is better than classical/pseudo prototypal inheritance and why i shouldn't use "new"](https://stackoverflow.com/questions/20266358/understanding-why-true-prototypal-inheritance-is-better-than-classical-pseudo-pr) – Bricky Jul 19 '17 at 21:03
  • also [What's the Best way to create Javascript Classes?](https://stackoverflow.com/questions/13190097/whats-the-best-way-to-create-javascript-classes/13190493#13190493), [Use of 'prototype' vs. 'this' in JavaScript?](https://stackoverflow.com/questions/310870/use-of-prototype-vs-this-in-javascript), [Object Oriented questions in Javascript](https://stackoverflow.com/questions/444170/object-oriented-questions-in-javascript) – Bricky Jul 19 '17 at 21:11

2 Answers2

0

There's not a major difference. Javascript doesn't have traditional Classes. Everything is just an Object and the syntax of example A is basically just around because of convention and Javascript trying to cater to both OOP and functional programming.

But only the first pattern allows you to make private variables, through the use of a closure.

Bricky
  • 2,572
  • 14
  • 30
-1

You get the same result. Class is a syntactic sugar in latest version of ECMAScript(ES). JavaScript is still prototype based, so you should be carefull about refrence on sepcial word this because for example:

class ExampleA {
    constructor() {
        this.text = 'Hello World!'
    }
    method() {
        console.log(this.text);
    }
}


let a = new EampleA()
a.method() // will print 'Hello World'
let m = a.method;
m() // will throw exception "Cannot read property 'text' of undefined
let b = {text: 'Hi'};
m.call(b) // will print 'Hi'
maksimr
  • 4,891
  • 2
  • 23
  • 22