Link to home
Start Free TrialLog in
Avatar of elepil
elepil

asked on

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?
ASKER CERTIFIED SOLUTION
Avatar of David S.
David S.
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of elepil
elepil

ASKER

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?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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.
Avatar of elepil

ASKER

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?
JavaScript simulates constructors but it's just cloning an object each time.

Did you read the article?
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?
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

Avatar of elepil

ASKER

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.
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.
Avatar of elepil

ASKER

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.
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.
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()".
Avatar of elepil

ASKER

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