[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

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

Posted on 2014-08-09
16
Medium Priority
?
126 Views
Last Modified: 2014-08-11
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?
0
Comment
Question by:elepil
  • 7
  • 5
  • 2
  • +1
16 Comments
 
LVL 43

Accepted Solution

by:
David S. earned 668 total points
ID: 40252081
At least among developers who use jQuery, including myself, closures seem to be much more commonly used.
0
 
LVL 34

Assisted Solution

by:Slick812
Slick812 earned 668 total points
ID: 40252105
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
 

Author Comment

by:elepil
ID: 40252114
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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 43

Assisted Solution

by:Rob
Rob earned 664 total points
ID: 40252984
0
 
LVL 43

Expert Comment

by:Rob
ID: 40252997
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
 

Author Comment

by:elepil
ID: 40253215
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
 
LVL 43

Expert Comment

by:Rob
ID: 40253232
JavaScript simulates constructors but it's just cloning an object each time.

Did you read the article?
0
 
LVL 43

Expert Comment

by:Rob
ID: 40253240
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
 
LVL 43

Expert Comment

by:Rob
ID: 40253302
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
 

Author Comment

by:elepil
ID: 40253374
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
 
LVL 34

Expert Comment

by:Slick812
ID: 40253995
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
 

Author Comment

by:elepil
ID: 40254215
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
 
LVL 43

Expert Comment

by:Rob
ID: 40254663
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
 
LVL 43

Expert Comment

by:David S.
ID: 40254704
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
 

Author Closing Comment

by:elepil
ID: 40254731
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
 
LVL 43

Expert Comment

by:Rob
ID: 40254809
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

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: DanRollins
This article describes a JavaScript program that creates a maze made of hexagonal cells.  In Part 2 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7850-Hex-Maze-Part-2.html), we'll extend the program by adding a depth-…
Today, the web development industry is booming, and many people consider it to be their vocation. The question you may be asking yourself is – how do I become a web developer?
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

868 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question