1

I'm starting to learn javascript in little deep way, oop-like where possible, for example which are the expressions to write objects...

First, what's the difference between this:

    var ObjA = function () {
        this.methodA = function () {
            alert("I'm objA.methodA()");
        }
    }
    var a = new ObjA();
    a.methodA();

and this:

    var ObjB = function () {
        return {
            methodB: function () {
                alert("I'm objB.methodB()");
            }
        }
    }
    var b = new ObjB();
    b.methodB();

The result is the same. Can someone explain it to me in a "for dummies" way:

  1. In both cases am I writing an object?

  2. Are there differences? Or are these two ways to write the same thing?

  3. Are there other ways to write an object?

  4. If you have something more to comment about a JavaScript object I'll be very happy.

In addition, speaking about object's methods, if I try:

    var ObjA = function () {
        this.methodA = function () {
            alert("I'm objA.methodA()");
        }

        this.methodPublic = function () {
            alert("I'm objA.methodPublic()");
            methodPrivate();
        }
        var methodPrivate = function () {
            alert("I'm objA.methodPrivate()");
        }
    }
    var a = new ObjA();
    a.methodPublic(); // OK
    a.methodPrivate(); // KO
  • When I call a.methodPublic(); --> I receive the methodPublic's alert, methodPublic() internally calls methodPrivate() and I receive methodPrivate()'s alert
  • When I call a.methodPrivate(); --> I recevie debugger error so:

    1. the name of the methods are right, that is I can say that "var mathodPrivate()" is like a private method, and "this.methodPublic()" is a public method?
    2. Are there other ways to write method inside objects? Are there other comments to be done about it?
Falco
  • 1,458
  • 3
  • 19
  • 47
  • 3
    `new` in the second example has no effect. It could be removed with the same outcome. –  Mar 19 '17 at 18:14
  • 2
    There are differences: `a instanceof ObjA` is `true`; `b instanceof ObjB` is `false`. – gyre Mar 19 '17 at 18:14
  • ok... even for the second part of the answer I found myself some explaination here: http://stackoverflow.com/questions/55611/javascript-private-methods – Falco Mar 19 '17 at 19:18
  • 1
    ProTip: Get out of the habit of using `alert()` for debugging. You'll find `console.log()` and `console.error()` will make your life much better. developer.mozilla.org/en-US/docs/Web/API/Console In this case, using `console.error()` will show you the call stack. – cloudworks Mar 20 '17 at 06:27

0 Answers0