Ancient town of JS (Before ES6)

Class without ES6:

new keyword does 5 things:

a. It creates a new object. The type of this object is simply object.
b. It sets this new object’s internal, inaccessible, [[prototype]] (i.e. proto) property to be the constructor function’s external, accessible,
prototype object (every function object automatically has a prototype property).
c. It makes the this variable point to the newly created object.
d. It executes the constructor function, using the newly created object whenever this is mentioned.
e. It returns the newly created object, unless the constructor function returns a non-null object reference. In this case, that object reference is returned instead.

example:

function Foo() { 
return this;
}
var a = Foo(); //returns window object
var b = new Foo(); //returns empty object of foo
console.log(a instanceof Window); // true
console.log(a instanceof Foo); // false
console.log(b instanceof Window); // false
console.log(b instanceof Foo); // true

without new:

var Foo = function(){
this.A = 1;
this.B = 2;
};
/**
Below function will add two properties to the window object (A and B).
It adds it to the window because window is the object that called the function when you execute it like that, and this in a function is the object that called the function
**/
Foo();
// Here bar is now an object with the properties A and B
var bar = new Foo();

Note: class keyword is reserved for future use (present in ES6), that’s why we use .className not .class to set a CSS class also in reactJS (JSX)

apply, call and bind:

The difference is that apply lets you invoke the function with arguments as an array;
call requires the parameters be listed explicitly.
A useful mnemonic is “A for array and C for comma.”

example:

theFunction.apply(this, arrayOfArgs)
theFunction.call(this, arg1, arg2, ...)

Bind creates a new function that will have this set to the first parameter passed to bind().

example:

var sum = function(a, b) {
return a + b;
};
var add5 = sum.bind(null, 5);
console.log(add5(10)); // 15

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Priyanshu Chauhan

Priyanshu Chauhan

JS fan

More from Medium

12 Useful JavaScript Newsletters

JavaScript vs ECMAScript

Quick Look About Javascript And Javascript Functions

JavaScript Variable Keywords