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:
In both cases am I writing an object?
Are there differences? Or are these two ways to write the same thing?
Are there other ways to write an object?
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:
- 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?
- Are there other ways to write method inside objects? Are there other comments to be done about it?