I am very new in creation of libraries in javascript and encapsulations in javascript. I created very first library with the help of one or two tutorials from the web.
The example looks like the following,
<script>
var libs=[];
(function(libs){
function firstLibrary (){
this.initializeHoldings = function () {}
this.myLibrary = function(){
var _myLibraryObject = [{FirstName: 'Ibrahim', LastName: 'Shaikh', CompanyName: 'Plexitech'},
{FirstName: 'Nizam', LastName: 'Siddiqui', CompanyName: 'Neoquant'}];
return _myLibraryObject;
}
}
libs.customLibrary = firstLibrary;
})(libs);
let $ = new libs.customLibrary();
console.log($.myLibrary());
</script>
This is how my code looks,
now the confusions are,
1): What are the difference between libraries and encapsulations in
javascript?
2): How can I create library without encapsulating it in javascript?
3): Does encapsulation always create library?
Yes, I know it might be a silly question for some of you but many newbies might get confused on this.
1): What are the difference between libraries and encapsulations in javascript?
A "library" is a set of functions/classes. "Encapsulation" doesn't really have a meaning as a unit of code like "library." Wikipedia's short definitions of "encapsulation" are pretty good:
A language mechanism for restricting direct access to some of the object's components.
A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data.
As you can see, neither means anything like "library." But you would probably use encapsulation in parts of your library.
2): How can I create library without encapsulating it in javascript?
Probably, if you didn't have any data maintained by the library that you needed to prevent other code from using, and didn't need to combine data with methods.
3): Does encapsulation always create library?
No, not at all. They're largely unrelated terms and concepts.
Related
I'm trying to interpret this piece of Javascript code. What is the use of the $ and _ signs here? In particular, is $ an alias for the JQuery library, and does this also apply for $set?
Template.postEdit.events({
'submit form': function(event) {
event.preventDefault();
var currentPostId = this._id;
var postProperties = {
url: $(event.target).find('[name=url]').val(),
title: $(event.target).find('[name=title]').val()
}
Posts.update(currentPostId, {$set: postProperties}, function(error) {
if (error) {
// display the error to the user
throwError(error.reason);
} else {
Router.go('postPage', {_id: currentPostId});
}
});
}
});
Explaination
$ and _ are mostly appended in Javascript variables to give more readability and to be more distinguishable ( visually most of the times ) from other variables. They are just conventions used by JS developers. Not necessary you've to use them. Major libraries/frameworks like Jquery, Angular like to follow this style in their frameworks.
Usage of $
Jquery have wrapped their features in $ . If you have included jQuery in your application, then $ used alone stands for jquery Object. Jquery being a really popular modern library, have somehow snatched the variable in JS. But its not like they have licensed the variable ( Just think, if variable name could be licensed, development would be more painful than it is now :p ), its more like they have dominated the use of $.
var selector = $('.someclass'); /* This is jquery object similar to
var selector = jQuery('.someclass') */
var $somestring = 'some string'; // Here $ character is appended to a variable.
//It doesn't adds any special behavior to the variable.
Some people have make good use of $, check it out here.
A naive developer who have used too much or the only library as JQuery in his lifespan is prone to this confusion. When he sees source code from framework like AngularJS, he tries to relate things with his former love jQuery. In Angular variables like $scope, $compile, etc, they seem confusing to him, as they have heavily appended $ to name their objects. Its just another name, you can write code with or without it. Angular uses this convention to distinguish variables from local to special objects. Big guns always try to dominate their conventions over the developer community. Can't blame them much, its for the betterment for all
Usage of _
Riding in similar vogue bandwagon, _ was nearly snatched by another useful ( really ? we can live without it ) library called Underscore Js . So they use the _ as their Underscore object, or mostly developers are to be blamed for this abuse, as they have paved its path to the vanity. But we can't blame developers for this, they were just using following good naming conventions.
var _myName = 'Who Cares'; // similar to $ no special behavior
var currentPostId = this._id; // In your case it seems
Well _ is mostly used by developers to distinguish the variables as private data members of their class, but only naming doesn't guarantee the access level. A good post briefly explaining for this is here
The best part is that, all the special characters that are allowed in Javascript to create distinguishable variable names are already invaded by biggies. So no more confusion. It is understandable why underscore invaded _ as their supremo, it stands for its meaning. But I am still curious why $ was chosen by jQuery. It doesn't even rhyme with it. No distant relation, it seems jQuery just took it as their property. I don't find any post explaining their invasion over it.
Sorry for being so dramatic, comic and sarcastic. Feel free to downnvote if it does not suit your appetite. Here to just help and make this space more interesting.
P.S : A list of valid characters for the naming convention used in JS
is explained here
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I can't get my head around OOP in JavaScript.
Many years ago, I used to dabble in programming BASIC and learned a bit of COBOL and FORTRAN in school so I am somewhat familiar with procedural programming, but I never learned any of these to a very high level of proficiency or complexity. I've also done a few hackey things with JS but I guess it was mostly procedural in nature rather than OOP.
Recently, I've decided to train myself to become a web developer and learn JavaScript properly, and based on the rave reviews, I decided on Head First JavaScript Programming as my textbook.
The problem I am having is that I can't figure out how or why using objects is really any different or better than using functions and variables. I've looked around at a ton of tutorials and videos but they all say the exact same thing as the book. "Objects are useful because they are analogous to everyday items in real life such as a car. A car has a model year, a make, a weight, a color, etc... A car can also do things such as start, stop, go, etc. They are functions inside the object and called 'methods'." and that is followed by "this is how to create an object:"
var myCar = {
make: "Chevy";
year: 2004;
kilograms: 2000;
color: "blue";
go: function() {
alert("go!");
}
};
Great. Now I know that objects are somehow analogous to real life things and I know how to make one with properties and methods. I get that.
And I can access these property values by calling them as follows:
a = myCar.make;
b = myCar.year;
c = myCar.color;
I can also call the function (or method):
myCar.go();
Wonderful. But I STILL can't figure out WHY I want to do it this way. Why is this better than the following?
myCarMake = "Chevy";
myCarYear = 2004;
myCarKgs = 2000;
myCarColor = "blue";
function go() {
alert("go!");
};
Other than how the code is organized, I don't understand how it's any less procedural. Statements are executed in order, after all. And I don't see what the advantages are to doing all of this.
I keep thinking that what I really need in order to understand this is to see two programs that do the same thing, one coded procedurally with normal variables and functions, and the second one programmed with OO in order to see the difference and how these objects interact with each other in an advantageous way.
I find that all the textbooks and websites that I have found never explain how similar things behave differently or why one is better than the other and there are few if any examples of how to tie it all together well. Most books and tutorials just tell you what you can do but not why you'd want to do that or choose one way over an other. (Irrelevant to this question but another thing I'm wonder about is, I know I can assign a function to a variable but WHY would I want to do that?)
To be clear about what I am looking for, my question is, can someone show me a program that is programmed both ways (both do the same thing and are simple enough for a beginner but complex enough to show why OOP might be needed or advantageous) to highlight the differences and explain why it's better?
In practice, if you have a small script or application, you will not see the difference.
But once you move towards larger applications and bigger code bases, you'll see that OOP works much better than PP.
Here are some high-level advantages of the OOP approach over the PP:
1) Modularity and maintainability
The code becomes modular, the related data and methods are packaged into objects.
This makes it much easier to keep the code under control.
It is complex to see this on few lines of code, but as your code grows, the procedural code most often turns into a mess.
With OOP your code is naturally splitted into smaller parts (objects) and even as the codebase grows, it is still easy to keep the code in order.
The modularity leads to better maintainability - it is easier to modify and maintain the code.
2) Flexibility
It is much easier to replace the part of the code with some different functionality.
For example, you can have the Logger object which writes logs to files. But then you decide to write logs to the database instead.
With PP approach you would need to go over the whole code base searching for something like log_to_file(message, file_name) and replace with something like log_to_db(message, db, table_name).
With OOP you just create the new DbLogger and "plug it" into the system instead of the previous file logger, so the code which logs data will still look the same, like logger->log(message). Even better, you can decide on the type of the logger run-time, for example, read the setting from the configuration file and create whether file logger or db logger.
3) Testability
With OOP it is much easier to take our part of the code (object) and test it alone. If it depends on other objects, these can be replaced with fake implementations (test mocks), so you can really test the piece of code alone.
Just to demonstrate the difference, let's imagine that instead of one car, you now have three (also the go method should really do something with the variables, otherwise it doesn't make much sense):
var myCarMake = "Chevy";
var myCarYear = 2004;
var myCarKgs = 2000;
var myCarColor = "blue";
var yourCarMake = "Ford";
var yourCarYear = 2001;
var yourCarKgs = 1990;
var yourCarColor = "white";
var hisCarMake = "Ferrari";
var hisCarYear = 2011;
var hisCarKgs = 2990;
var hisCarColor = "red";
function go(make, year, kgs, color) {
alert(make + " " + kgs + " " + year + " " color);
};
go(myCarMake, myCarYear, myCarKgs, myCarColor);
go(yourCarMake, yourCarYear, yourCarKgs, myCarColor);
go(hisCarMake, hisCarKgs, hisCarKgs, hisCarColor);
Notice some of the properties of this code:
busness-logic code (the definition of car properties and the go method) is mixed with the client code (the part where we call go), we can not separate them, because client code refers to the global variables we created (like myCarMake)
many repetitions (like CarMake is written 6 times) and it looks messy
easy to make the error (there are errors in last two calls)
hard to maintain - if we add a new parameter for the car, we will have to go over all the code base
Now the version with object (to simplify the code, I keep it as a simple object and separate constructor function, see this for other ways to define the object):
var CarPrototype = { // empty object-prototype
make: "",
year: 0,
kilograms: 0,
color: "",
go: function() {
alert(this.make + " " + this.kgs + " " + this.year + " " this.color);
}
};
// function that constructs the new object
function createCar(make, kgs, year, color) {
var car = Object.create(CarPrototype);
car.make = make;
car.kgs = kgs;
car.year = year;
car.color = color;
return car;
}
var myCar = createCar("Chevy", 2004, 2000, "blue");
var yourCar = createCar("Ford", 2001, 1990, "white");
var hisCar = createCar("Ferrari", 2011, 2990, "red");
myCar.go();
yourCar.go();
hisCar.go();
And some properties of this code:
the business logic is clearly defined and separated from the client code, client code is not aware of internal structure of the car object
less repetitions and in general the code looks clearer
once the object is defined, it is really complex to make the error (you just do myCar->go(), no parameters passing, no chance to mix them or pass in the wrong order
easier to modify (if we add a new property for the car, the myCar.go() calls in client code don't need to be changed)
For sure, I didn't mention all the reasons to use OOP over PP, but I know this from practice - try to spend some time learning OOP principles and start using it and you'll see the huge improvement in code structure. You will make mistakes and do things wrong in the beginning, but the result will anyway be better than procedural code.
The general approach here is more important than specific language constructs, you can use same principles in C (which is not an OOP language) and in javascript (which has a specific OOP support) as well as in other languages.
I don't know a resource which compares PP and OOP side by side, but I think you don't really need it. Just look at examples of OOP applications and imagine how these would look like if written in procedural style.
My favorite book about OOP is Design Patterns, it demonstrates how elegant and powerful can be interaction between objects.
Probably, you will also need to find something where basic OOP concepts are explained (already mentioned encapsulation, polymorphism, inheritance) and principles (most notably SOLID).
Truthfully, I always found the idea of properly scoped variables a good argument for the OOP approach of javascript.
Taking your example for instance:
var myCar = {
make: "Chevy",
year: 2004,
};
var make = "Ford";
console.log(make);
console.log(myCar.make);
Yields "Ford", then "Chevy". The reason scoping can be an issue within JS is the sheer number of libraries that can be pulled in. Yes small programs tend to be easier to write using procedural. But when you are pulling in a dozen other libraries, you do not know which approach they use for declaring variables - which can lead to obscure errors.
Yes, you could just declare the variables within the function definition and they would then be scoped to just that function (example below), but then they can't easily be reused!
function go(){
var make = "chevy";
console.log(make);
};
go();
console.log(make) ///throws undefined 'error'
OOP provides an approach that is scope safe, and easy to reuse (which is great for external libraries).
They say OOP is about inheritance, polymorphism and encapsulation.
We will leave encapsulation aside, as it has nothing to do with OOP, but rather with modules. (At last, modules are the part of the language!)
Inheritance is a powerful concept that makes possible to reuse both logic and data. Extending your car example, we can do the following.
var AbstractCar = {
go: function () {
alert('go ' + this.make+ '!');
}
};
var MyCar = Object.create(AbstractCar, {
make: { value: 'Chevy', writable: true }
});
var YourCar = Object.create(AbstractCar, {
make: { value: 'Mustang', writable: true }
});
MyCar.go(); // go Chevy!
YourCar.go() // go Mustang!
Polymorphism, on the other hand, allows you to treat different kinds of objects as one, as long as they conforms to the interface. Or, in the other words, as long as they can do want we want them to do.
For example, we need a string representation for out objects. Anything, that has a toString method could be concatenated with a string.
var myCar = {
make: "Chevy",
year: 2004,
toString: function () {
return this.make + ' ' + this.year;
}
};
var statement = 'I want to sell ' + myCar;
console.log(statement); // I want to sell Chevy 2004
And that's really it.
OOP is not some superior technique that should be mastered for what its worth. Though it can pretty handy. : )
I am wondering (perhaps more so from a UML point of view) how others have managed to document JavaScript objects successfully.
JavaScript can be expressed as OOP but in addition to these objects, files may also contain 'lose standing' scripts, which belongs to the file itself - not the object you defined.
Would you document the file itself as a class, and the classes it contain as nested classes?
Someone adapted UML for web artifact, its called the "WAE" extension of UML.
If you work with node.js, i created a module that generate class diagram for javascript/node/html/css. Its called wavi. For javascript, function,variable are automatically recognized. You can use it for documenting your application.
https://www.npmjs.org/package/wavi
No, it wouldn't make sense to document a JavaScript file as a class (with inner classes), but the "classes" it contains may be documented with a UML class diagram. However, since there is no explicit class concept in JavaScript, people use different code patterns for defining a "class". The most commonly used code pattern is the constructor-based definition of classes as proposed on the Mozilla website. In this approach, the constructor function (say, C) represents the class. It defines a number of properties (using this) and a number of methods/functions (using C.prototype). Then, in a UML class diagram, these properties and methods can be described in the form of a class rectangle.
If you want to document your javascript objects, you can even use a MVC pattern for javascript projects. I would personally try to avoid using innerclasses and use proper relationships between classes. If you mean with innerclasses; putting multiple classes sepperated in the same js file, then; yes that's a valid option. Javascript doesn't care in which file a class is, it only thinks about the classes (unlike Java if I'm correct).
Example I wrote 8 years ago for school showing the Control class:
function Control()
{
var myView = new View(respondOnChoice);
var myMathTest = new MathTest();
var myExercise = new Exercise();
function respondOnMathTestChoice()
{
myView.emptyMainDiv();
myView.showNameAndClassChoice();
}
}
Start.js (to initiate the control):
if (window.attachEvent) //IE
{
window.attachEvent("onload", initApp);
}
if (window.addEventListener)//Firefox
{
window.addEventListener("load", initApp,false);
}
function initGame()
{
var myControl = new Control();
}
In my opinion, this is the best way to use OOP in javascript. If you program properly, you won't have to mind about anything to do with innerclasses, just relationships between classes.
I'm re-writing a fairly complex script that I created a few weeks ago. After showing it to a few people, they all agreed that I should break it up into smaller pieces (classes) that have a specific purpose, and SOLID object-oriented programming principles
As a self-taught programmer these concepts are pretty new to me, and I'm a little confused about how to best transfer data from one function/class to another. For instance, here is a simplified structure of what I'm building:
MY QUESTION IS:
Should I have a "controller" script that calls all of these functions/classes and passes the data around wherever necessary? Is this where I would put the for loop from the diagram above, even though it would work just as well as part of Function 1 which could then call Function 2?
Without a controller/service script you'll not be able to meet single responsibility principle in fact. Here's a high level design I'd implement if I were you.
FileRepository
Should expose a method to get a file. Let's name it GetFileById.
MongoDBRepository
Methods for CRUD operations. Such as SelectById, SelectByQuery, Update, Create, Delete.
Object creation logic
If your createNewObj logic is simple it would be enough to move it to your object contructor so that your code looks like that: var newObj = new MyObj(json[i]);
But if it's relatively complex maybe because you use some third party frameforks for validation or whatever you'd better create a factory. Then you could would look this way: var newObj = MyObjFactory.Create(json[i]);
Service/controller
Finally you'll need to implement controller/service object. Let's name it WorkService with a method DoWork which should handle all interactions between the repositories and other objects discribed above. Here's approximately DoWork should look like:
function DoWork(fileId){
var json = fileRepository.SelectById(fileId);
for(var i=0;i<json.length;i++){
var newObj = new MyObj(json[i]); // or calling factory method
var dbRecord = MongoDBRepository.SelectByQuery(newObj.name, newObj.date);
if(dbRecord){
MongoDBRepository.Update(newObj);
}
else{
MongoDBRepository.Create(newObj);
}
}
}
Please note it's just a javascript syntax pseudo-code. Your actual code might look absolutley different but it gives your a feeling of what kind of design your should have. Also I exmplicitly didn't create a repository objects inside DoWork method, think of the way to inject them so you meet Dependency inversion principle.
Hope it helps!
Background
I'm trying to refactor some long, ugly Javascript (shamefully, it's my own). I started the project when I started learning Javascript; it was a great learning experience, but there is some total garbage in my code and I employ some rather bad practices, chief among them being heavy pollution of the global namespace / object (in my case, the window object). In my effort to mitigate said pollution, I think it would be helpful to measure it.
Approach
My gut instinct was to simply count the number of objects attached to the window object prior to loading any code, again after loading third-party libraries and lastly after my code has been executed. Then, as I refactor, I would try to reduce the increase that corresponds to loading my code). To do this, I'm using:
console.log(Object.keys(window).length)
at various places in my code. This seems to work alright and I see the number grow, in particular after my own code is loaded. But...
Problem
Just from looking at the contents of the window object in the Chrome Developer console, I can see that its not counting everything attached to the object. I suspect it's not including some more fundamental properties or object types, whether they belong to the browser, a library or my own code. Either way though, can anyone think of a better and more accurate way to measure global namespace pollution that would help in refactoring?
Thanks in advance!
So after some of the comments left by Felix Kling and Lèse majesté, I have found a solution that works well. Prior to loading any libraries or my own code, I create the dashboard global object (my only intentional one) and store a list of objects attached to window via:
var dashboard = {
cache: {
load: Object.getOwnPropertyNames(window)
}
};
Then, after I load all of the libraries but prior to loading any of my own code, I modify the dashboard object, adding the pollution method (within a new debug namespace):
dashboard.debug = {
pollution: (function() {
var pollution,
base = cache.load, // window at load
filter = function(a,b) { // difference of two arrays
return a.filter(function(i) {
return !(b.indexOf(i) > -1);
});
},
library = filter(Object.getOwnPropertyNames(window), base),
custom = function() {
return filter(Object.getOwnPropertyNames(window),
base.concat(library));
};
delete cache.load;
pollution = function() {
console.log('Global namespace polluted with:\n ' +
custom().length + ' custom objects \n ' +
library.length + ' library objects');
return {custom: custom().sort(), library: library.sort()};
};
return pollution;
}())
};
At any point, I can call this method from the console and see
Global namespace polluted with:
53 custom objects
44 library objects
as well as two arrays listing the keys associated with those objects. The base and library snapshots are static, while the current custom measurement (via custom) is dynamic such that if I were to load any custom javascript via AJAX, then I could remeasure and see any new custom "pollution".
The general pattern you've selected works OK from experience. However, there are two things you might need to consider (as additions or alternatives):
Use JsLint.com or JSHint.com with your existing code and look at the errors produced. It should help you spot most if not all of the global variable usage quickly and easily (you'll see errors of 'undefined' variables for example). This is a great simple approach. So, the measurement in this case will be just looking at the total number of issues.
We've found that Chrome can make doing detection of leaking resources on the window object tricky (as things are added during the course of running the page). We've needed to check for example to see if certain properties returned are native by using RegExs: /\s*function \w*\(\) {\s*\[native code\]\s*}\s*/ to spot native code. In some code "leak detection" code we've written, we also try to (in a try catch) obtain the value of a property to verify it's set to a value (and not just undefined). But, that shouldn't be necessary in your case.