Skip to main content

Javascript notes

What is the difference between call and apply?


The difference is that apply lets you invoke the function with arguments as an array; callrequires the parameters be listed explicitly. A useful mnemonic is "A for array and C for comma."
See MDN's documentation on apply and call.
Pseudo syntax:
theFunction.apply(valueForThis, arrayOfArgs)
theFunction.call(valueForThis, arg1, arg2, ...)
Sample code:
function theFunction(name, profession) {
    alert("My name is " + name + " and I am a " + profession + ".");
}
theFunction("John", "fireman");
theFunction.apply(undefined, ["Susan", "school teacher"]);
theFunction.call(undefined, "Claude", "mathematician");

Map vs Object in JavaScript


According to mozilla:
A Map object can iterate its elements in insertion order - a for..of loop will return an array of [key, value] for each iteration.
and
Objects are similar to Maps in that both let you set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. Because of this, Objects have been used as Maps historically; however, there are important differences between Objects and Maps that make using a Map better.
An Object has a prototype, so there are default keys in the map. However, this can be bypassed using map = Object.create(null). The keys of an Object are Strings, where they can be any value for a Map. You can get the size of a Map easily while you have to manually keep track of size for an Object.
Use maps over objects when keys are unknown until run time, and when all keys are the same type and all values are the same type.
Use objects when there is logic that operates on individual elements.

Bind creates a new function that will have this set to the first parameter passed to bind().
Here's an example that shows how to use bind to pass a member method around that has the correct this:
var Button = function(content) { 
  this.content = content;
};
Button.prototype.click = function() {
  console.log(this.content + ' clicked');
}

var myButton = new Button('OK');
myButton.click();

var looseClick = myButton.click;
looseClick(); // not bound, 'this' is not myButton

var boundClick = myButton.click.bind(myButton);
boundClick(); // bound, 'this' is myButton
Which prints out:
OK clicked
undefined clicked
OK clicked
You can also add extra parameters after the 1st parameter and bind will pass in those values to the original function before passing in the extra parameters you pass to the bound function:
// Example showing binding some parameters
var sum = function(a, b) {
  return a + b;
};

var add5 = sum.bind(null, 5);
console.log(add5(10));
Which prints out:
15
Check out JavaScript Function bind for more info and interactive examples.

How do JavaScript closures work?


Two one sentence summaries:
  • a closure is the local variables for a function — kept alive after the function has returned, or
  • a closure is a stack-frame which is not deallocated when the function returns (as if a 'stack-frame' were malloc'ed instead of being on the stack!).
The following code returns a reference to a function:
function sayHello2(name) {
    var text = 'Hello ' + name; // Local variable
    var sayAlert = function() { alert(text); }
    return sayAlert;
}
var say2 = sayHello2('Bob');
say2(); // alerts "Hello Bob"
There is a critical difference between a C pointer to a function and a JavaScript reference to a function. In JavaScript, you can think of a function reference variable as having both a pointer to a function as well as a hidden pointer to a closure.
The above code has a closure because the anonymous function function() { alert(text); } is declared inside another function, sayHello2() in this example. In JavaScript, if you use the function keyword inside another function, you are creating a closure.
In C, and most other common languages after a function returns, all the local variables are no longer accessible because the stack-frame is destroyed.
In JavaScript, if you declare a function within another function, then the local variables can remain accessible after returning from the function you called. This is demonstrated above, because we call the function say2() after we have returned from sayHello2(). Notice that the code that we call references the variable text, which was a local variable of the function sayHello2().
function() { alert(text); } // Output of say2.toString();
Looking at the output of say2.toString(), we can see that the code refers to the variable text. The anonymous function can reference text which holds the value 'Bob' because the local variables of sayHello2() are kept in a closure.
The magic is that in JavaScript a function reference also has a secret reference to the closure it was created in — similar to how delegates are a method pointer plus a secret reference to an object.

All collaborations are made from StackOverflow.

Comments

  1. I started on COPD Herbal treatment from Ultimate Life Clinic, the treatment worked incredibly for my lungs condition. I used the herbal treatment for almost 4 months, it reversed my COPD. My severe shortness of breath, dry cough, chest tightness gradually disappeared. Reach Ultimate Life Clinic via their website www.ultimatelifeclinic.com . I can breath much better and It feels comfortable!

    ReplyDelete

Post a Comment

Popular posts from this blog

Trip to narsipura Sri Vaidya Narayana murthy - Shimago for cancer treatment

Hi friends. I would like to share my experience about my trip to Shimago and meet Guru Narayana murthy who would treat for cancer, diabetics, kidney diseases. My brother was diagnosed with rectal cancer on October 2014. The news of cancer to a young boy of 26 years shook our whole family. But we are strong as he was getting treatment from world class care clinic in Cleveland - Cleveland clinic, Ohio, USA. As fate had other plans, his cancer came in January, 2017 back after an extensive surgery, chemotherapy and radiotherapy. The doctors made a decision to keep him in hospice care: support for advanced illness. They said that there is no more treatment and only to keep him comfortable as long as he lives, we lost our hopes and that is when we thought of giving a try to Ayurvedic medicine. We found Guruji narasipura narayana murthy. His medicine gave us hopes and I recently went to narsipura to get the medicine. I thought it would be best to give my share of experience in reaching the

Solution to "child margin affects parent" in CSS

The browser implementation is that when the parent has no content and the child requests for margin, the parent is brought down instead of child going down. The solution for these are listed below with their side effects. floats , You  have  to float elements border-top , This pushes the parent at least 1px downwards which should then be adjusted with introducing  -1px  margin to the parent element itself. This can create problems when parent already has  margin-top  in relative units. padding-top , same effect as using  border-top overflow: hidden , Can't be used when parent should display overflowing content, like a drop down menu overflow: auto , Introduces scrollbars for parent element that has (intentionally) overflowing content (like shadows or tool tip's triangle) See the Pen Relative with Margin by Manikanta ( @immnk ) on CodePen .