Closures:: Prototype: Function's Prototype
Closures:: Prototype: Function's Prototype
$(document).ready(function(){
var a = 10;
$(‘#button’).click(function(){
console.log(a); //Since a is referenced from inner function, it will not be
garbage collected even when outer function has completed execution and will be accessible
from within this function.
});
});
Prototype:
● Function’s prototype:
○ A function’s prototype is an object instance (empty initially) that will become
the prototype for all objects created using this function as constructor.
● Object’s prototype:
○ An object prototype is the object instance from which the object is inherited.
● Inhertance:
○ Inheritance can be achieved in javascript using prototypical inheritance.
○ Let us take an example,
Suppose there is a base class called “Person” which has properties defined
within constructor and methods defined on prototype object.
Person.prototype.getAge = function() {
//Calculate age based on value of this.dob and set it to local variable
“age”
return age;
}
Now, I want to create a class called Teacher which will inherit all properties
and methods from Person class and have additional properties and methods.
Derived class can inherit own properties of base class by calling constructor
of base class from constructor of child class passing child class context to it, i.e.
Teacher.prototype = Object.create(Person.prototype);
This will set prototype object of child class to be equal to that of parent class.
However, this will also set “Teacher.prototype.constructor” property to “Person” which
we do not want. We want this to be set to “Teacher”. And this can be fixed as follows,
Teacher.prototype.constructor = Teacher;
Once this is done, we can define additional properties / functions on prototype object
of Teacher class.
Hoisting:
● The purpose of “use strict” is to indicate that code is to be executed in strict mode.
● When strict mode is enabled,
○ You cannot use undeclared variables.
○ Eliminates javascript silent errors by changing them to throw errors.
○ It restricts use of keywords / syntax likely to be defined in next version of
ecmascript.
● Benefits of strict mode:
○ Strict mode changes previously accepted “bad syntax” into real errors.
○ In JavaScript mistyping a variable name creates a new global variable. In strict
mode, this will throw an error, making it impossible to accidentally create a
property of window variable.
○ In normal JavaScript, a developer will not receive any error feedback assigning
values to non-writable properties. And also any assignment to a non-writable
property, a getter-only property, a non-existing property, a non-existing variable,
or a non-existing object, will throw an error.
function connectToSomething() {
//Code for connecting to something
eventEmitter.emit(“connected_to_something”);
}
eventEmitter.on(“connected_to_something”, function() {
console.log(“Established connection!”);
});
Asynchronous Programming:
Event Loop: