Write your own javascript library

https://egghead.io/series/how-to-write-an-open-source-javascript-library?__s=fhupaiyhqvu3yop57t6b&utm_campaign=publishing-an-open-source-javascript-library&utm_medium=email&utm_source=publishing-an-open-source-javascript-library

Advertisements

Why we will use Prototypes in javascript

What is the different between these 2 snippets of code:

function animal(){
    this.name = 'rover';
    this.set_name = function(name){
         this.name = name;
    }
}

function animal(){
    this.name = 'rover';
}
animal.prototype.set_name = function(name){
    this.name = name;
}

They both do the same thing, so whats the difference?

 

Using the prototype makes for faster object creation, since that function does not have to be re-created each time a new object is created.

When you do this:

function animal(){
    this.name = 'rover';
    this.set_name = function(name){
         this.name = name;
    }
}

The set_name function is created de novo each and every time you create an animal. But when you do this

animal.prototype.set_name = function(name){
    this.name = name;
}

The function does not have to be re-created each time; it exists in one place in the prototype. So when you call someAnimal.set_name("Ubu"); the this context will be set to someAnimal and (the one and only) set_name function will be called.


There is one advantage to using the first syntax though: functions created in this manner will have access to private data:

function animal(){
    var privateData = 'foo'

    this.name = 'rover';
    this.set_name = function(name){
         this.name = name;
         alert(privateData); //will alert 'foo'
    }
}

Douglas Crockford calls functions created like this “privileged” for that reason: they have access to both public, and private data.

Difference between Loosely coupled and tightly coupled in programming sense

Tight coupling is when a group of classes are highly dependent on one another.

This scenario arises when a class assumes too many responsibilities, or when one concern is spread over many classes rather than having its own class.

Loose coupling is achieved by means of a design that promotes single-responsibility and separation of concerns.

A loosely-coupled class can be consumed and tested independently of other (concrete) classes.

Interfaces are a powerful tool to use for decoupling. Classes can communicate through interfaces rather than other concrete classes, and any class can be on the other end of that communication simply by implementing the interface.

Example of tight coupling: