How do JavaScript professionals create "classes" -- closure or functions?

I'm in the transition of changing technologies in my programming career. I come from a classic object-oriented language (Java), and I'm trying to familiarize myself more in JavaScript.

What is the most common practice today by JavaScript developers when they have to create a data object that needs to respect private and public properties and methods? Do they create the object via closure? Or constructor functions?
elepilAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

David S.Commented:
At least among developers who use jQuery, including myself, closures seem to be much more commonly used.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Slick812Commented:
greetings elepil, although javascript has object oriented language protocols, it is also a stand alone function setup,, but it is NOT a "class definition" set as used in other languages (java, etc.). So as to your question about "What is the most common practice today", , I do believe that many use either as the code will benefit from a closure {} or a function.

As far as talking about  - "data object that needs to respect private and public properties and methods", this is not something that is considered very much in javascript, as the concept of "private and public" is not generally applied to OBJECTS, and there are no class definitions (at least as used in java). If you need to make functional objects in javascript with the "new" script word, then you are likely limited to  creating the objects via constructor functions. The concept of building and using class definitions (via functions) in javascript, is a different set of usage protocols and restrictions than in any other programming language.
0
elepilAuthor Commented:
Thank you for your elaborate response, Slick812.

I do realize JavaScript has no explicit keywords like "private" or "public", but it is nevertheless possible to create objects that have private/public properties and methods. When you said:

this is not something that is considered very much in javascript, as the concept of "private and public" is not generally applied to OBJECTS,

did you mean to say that JavaScript programmers knowingly do not bother to make private/public distinctions on properties/methods within objects they create?
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

RobOwner (Aidellio)Commented:
0
RobOwner (Aidellio)Commented:
More specifically, in my article "Javascript is just an object", the very first code example shows you how private and public variables / methods are created.  Publically available properties are "attached" to the parent object using the "this" operator, whilst private variables are instantiated using the var keyword.

So in a sense, it is about the scope of the variable / function but also about how the variable is "attached".

Anonymous functions are also covered, that do not attach to anything.  Run once and destroyed.
0
elepilAuthor Commented:
Thanks for your response, Rob. I think you might have misunderstood my question. I was interested in getting a feel among professional JavaScript developers on what method they use to create objects, i.e., through closure or constructor functions.

Which method do you use more often?
0
RobOwner (Aidellio)Commented:
JavaScript simulates constructors but it's just cloning an object each time.

Did you read the article?
0
RobOwner (Aidellio)Commented:
So to answer your question it does neither though I'm not sure what you mean by closure.   Haven't heard that term before but I may know it by another name. Can you give an example?
0
RobOwner (Aidellio)Commented:
Closure (http://en.wikipedia.org/wiki/Closure_(computer_programming)) definitely plays a part, if this is what you mean.  The variables / functions are defined in an function (that is an Object anyway) and persist via cloning when you instantiate them.

From my article:

function person(name, age, phone) {
	// some public variables	
	this.name = name;
	this.age = age;
	this.phone = phone;
	
	// a private! variable
	var all_details = name + " " + age + " " + phone;
	
	// public function	
	this.getDetails = function() {
		return all_details;
	};
}

Open in new window


Then instantiated by:
var newPerson = new person("Rob",30,"555-4255");
newPerson.getDetails(); //returns the string "Rob 30 555-4255"

Open in new window

0
elepilAuthor Commented:
Rob, I did go through your article, but it was more of a basic JavaScript tutorial. And yes, the link you provided about Closure is exactly what I was talking about.

But I think you answered my question indirectly, that you use function constructors and not closures to create your data objects, and I thank you for that.
0
Slick812Commented:
OK, I was talking about what the developer was going to do on their web page and the javascript that needs to be used to get the working elements of the page to function.

you ask - "did you mean to say that JavaScript programmers knowingly do not bother to make private/public distinctions on properties/methods within objects they create"

They most often are concerns about what will be in the function as a created object to have needed access to methods, and properties, as in java, but since the usage for access is mostly a given as

ob1.int1 = 101;
ob1.str1 = "a string";
ob1.method1("note1", 55, true);

ob2.meth("go near", ob1.pro1, someVar);

the considerations for relative assess scope (public, private) is different than in java or other languages. In javascript the variable, and object scope considerations have their own attachments and range, unlike java.

so the " knowingly do not bother to make private/public distinctions" is more or less true, however if the developer needs to have object and-or property access outside of the function definition, then changes can be made to have the scope widened (changed). But some will say that the public-private scope is "knowingly" set by development. But the "SCOPE" of access is different than java, no matter how you might think of the developer knowing about public-private.

But I have created many single instances of objects with the { } object definition, and it works. But can not do any input initialization.
0
elepilAuthor Commented:
Slick812, here's what I mean:

    function Person(firstName, lastName, gender) {
    /**
     * Private properties and methods
     */
    var _firstName = firstName;     // private property
    var _lastName = lastName;       // private property
    var _initials = function() {    // private method
        return _firstName.substr(0,1) + " " + _lastName.substr(0,1);
    }
    
    /**
     * Public properties and methods
     */
    // Public properties
    this.gender = gender;
 
    this.getFirstName = function() {
        return _firstName;
    };
   
    this.setFirstName = function(value){
        _firstName = value;
    };

    this.getLastName = function() {
        return _lastName;
    };
    
    this.setLastName = function(value) {
        _lastName = value;
    };
    
    this.toString = function() {
        return "[_firstName=" + this.getFirstName() + "][_lastName=" + 
                this.getLastName() + "][gender=" + gender + "][initials=" + 
                _initials() + "]\n\n";
    };

Open in new window


The above code snippet demonstrates respect for private/public properties, and private/public methods the way you'd see in classic object-oriented programming languages like Java. So it is totally possible to emulate classic object-oriented programming with JavaScript. The example above is using a constructor function, but it can easily be modified to become a closure instead.

I guess all I really wanted to do was get a feel from professional JavaScript developers on which way they go, and what you said sort of surprised me, that's all.

I'm leaving this ticket open for now, hoping to solicit more opinions from others, so thank you for your responses.
0
RobOwner (Aidellio)Commented:
If I could add that, yes it is a  basic tutorial but really JavaScript doesn't get more complicated than that. The article sites you how to create private and public properties.
It is important to note that it's a constructor however the class you create, so to speak, inherits everything from the parent Object class. E.g.they all have the toString() futon attached.
If you're interested about how professionals create frameworks using namespaces then have a read of my second tutorial about "JavaScript frameworks, what are they"
Then just download an unminified version of jQuery to also see how private and public objects are attached in a professional environment.
0
David S.Commented:
To briefly expand on what I said earlier, I rarely use the "this" keyword outside of event listeners/handlers. I prefer using closures and object literals to using constructors and prototypes.

So to answer your question it does neither though I'm not sure what you mean by closure.   Haven't heard that term before but I may know it by another name.
Really? Wow. Rob, I'm surprised you're not familiar for the term for that technique for controlling variable scope.

For anyone who might be interested, here's two good articles on them:
http://www.jibbering.com/faq/faq_notes/closures.html
http://robertnyman.com/2008/10/09/explaining-javascript-scope-and-closures/

But I have created many single instances of objects with the { } object definition, and it works. But can not do any input initialization.
That's known as an "object literal". Basically, it's shorthand for using "new Object()".
0
elepilAuthor Commented:
I think the conclusion I can make from your responses are that JavaScript developers use both closure and constructor functions. I can also see that it is a toss up, with none of you strongly criticizing one or the other, but rather, willingly accepting one or the other. This was all the "feel" I needed to get.

I thank you all for your responses.
0
RobOwner (Aidellio)Commented:
Really? Wow. Rob, I'm surprised you're not familiar for the term for that technique for controlling variable scope.
*laughing* so am I! and I've done a fair amount of using closures without knowing the technical name for it.  I've just called it the scope and their "life" or whether they persist, so my understanding of the technique is there just didn't have a name for it :).  

That's what I love about EE, is you learn something every day on both sides of the coin (asking questions and answering them).
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.