Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save nishantmendiratta/642538cb312bf57ec21821f3f60bef38 to your computer and use it in GitHub Desktop.
Save nishantmendiratta/642538cb312bf57ec21821f3f60bef38 to your computer and use it in GitHub Desktop.
JavaScript: Understanding the Weird Parts in 35ish minutes - Part 5/6
Credits
Prerequisite

Section 5 - Building Objects

Lesson 57- Function Constructors, 'new', and the History of Javascript

Example 1: Function constructor

function Person(){ //Constructor
	this.firstname = ‘John’;
	this.lastname = ‘Doe’;
}
//Creating new object using “new” keyword
var john = new Person();
console.log(john);
//OUTPUT Person { fistname: “John”,lastname: “Doe” }

Explanation - new keyword creates an empty object typeof Person and then Person function is invoked, Now this variable is pointing to empty object in memory so this.firstname and this.lastname being added upon empty object. Now js engine returns the object created by new keyword.

Example 2: Constructor with params

function Person(firstname, lastname){ //Constructor
	console.log(this); // Person {} 
	this.firstname =firstname;
	this.lastname =lastname;
}
var john = new Person(‘John’,’Doe’);

#BIGWORD Function Constructors - A normal function that is used to construct objects. The ‘this’ variable points to a new empty object, and that object is returned from the function automatically.

Lesson 58- Function Constructors and '.prototype'

The function constructor already set the prototype for you.

Example 1:

//Check following in console 
john.__proto__
//OUTPUT Person { } 

Functions are a special type of objects in javascript function has name property(optional can be anonymous), code property when we ()invoke it is invocable. Every function has a prototype property(used only by the new operator).

The prototype property of the function is not the prototype of the function it’s the prototype of any objects created if we are using the function as the function constructor.

All functions get special property (prototype)

Example 2:

function Person(firstname, lastname){ //Constructor
	console.log(this); // Person {} 
	this.firstname =firstname;
	this.lastname =lastname;
}
person.prototype.getFullName = function (){
	return this.firstname + ‘ ’ + this.lastname;
}
var john = new Person(‘John’, ‘Doe’);
console.log(john);
//OUTPUT
Person { firstname : ‘John’, lastname : ‘Doe’, getFullName : function }

john.getFullName(); // “John Doe”

We can add something to our prototype on the fly cuz prototype chain is just looking at these objects at the moment you try to access any one of these methods or properties.

Example 3:

Person.prototype.getFormalFullName = function (){
	return this.lastname + ‘, ‘ + this.firstname;
}
console.log(john.getFormalFullName()); //”Doe, John”

Lesson 59 - Dangerous Aside ('new' and Functions)

Example 1: We use the first letter as the capital letter in case of function constructor

function Person(firstname, lastname){ //Constructor
	console.log(this); // Person {} 
	this.firstname =firstname;
	this.lastname =lastname;
}
person.prototype.getFullName = function (){
	return this.firstname + ‘ ’ + this.lastname;
}

If we don’t use the new keyword, It will still execute the function but it returns undefined

var john = Person(‘John’, ‘Doe’);

so following line of code with throw an error, as we are accessing prototype of undefined

console.log(john.getFullName);

So always use the new keyword to access prototype properties

Lesson 60- Conceptual Aside (Built-In Function Constructors)

Try in console

var a = new Number(“3”);

a is not a primitive and not a number it’s an object because function construct returns an object

a // Number {[[ PrimitiveValue ]]: 3}
//Check Number.prototype which is all number objects will have access to 
like - a.toFixed() // “3.00”

Example 1:

String.prototype.isLengthGreaterThan = function(limit){
	//this is referred to the returning object
return this;.length > limit;	
}
//john is converted to an object automatically
console.log(“John”.isLengthGreaterThan(3)); //true

Example 2:

Number.prototype.isPositive = function(){
	return this>0;
}

3.isPostivie() 
//Error - SyntaxError 
//Reason - js automatically converts the string but not numbers to an object 

Working Example 2:

var a = new Number(3);
a.isPositive(); //true

Lesson 61- Dangerous Aside (Built-In Function Constructors)

Example 1:

var a = 3;
var b = new Number(3);
a == b //true both are primitive 
a === b //false but type of b is object
refer momentjs.com for dates

Lesson 62- Dangerous Aside (Arrays and for ..in)

Example 1 :

Array.prototype.myCustomFeature = ‘cool’;
var arr = [‘John, ’Jane’, ’Jim’];
for(var prop in arr){
	console.log(prop + “:” + arr[prop]);
}
//OUTPUT For in can read all properties of an array to avoid this always use for loop
0 : John
1 : Jane
2 : Jim
myCustomFeature : cool

Lesson 63- Object.create and Pure Prototypal Inheritance

Example 1: //Pure Prototypal Inheritance

//base object
var person = {
	firstname : ‘Default’,
	lastname : ‘Default,
	greet : function(){
		return ‘Hi ’ + this.firstname;
 }
}

var john = Object.create(person);
//This will return an empty object with __proto__ having all properties
console.log(john);
john.greet(); // “Hi Default”

//To hide old values 
john.firstname = ‘John’;
john.lastname = ‘Doe’;
console.log(john);
john.greet(); // “Hi John”

#BIGWORD Polyfill: Code that adds a feature which an engine may lack.

Example 1:

var person = {
	firstname : ‘Default’,
	lastname : ‘Default,
	greet : function(){
		return ‘Hi ’ + this.firstname;
    }
}

// Providing support to browsers which don’t have Object.create feature
var john = Object.create(person);

//Solving problem with polyfill
if(!Object.create){
	Object.create = function(o){
	if(arguments.length>1){
		throw new Error (‘Object.create impl accepts only first parameter’);
	}
	function F() {}
	F.prototype = o;
	   return new F();
  	};
}

Lesson 64 - ES6 and Classes

Just another way to create objects and set the prototype

Example 1:

//This class person is an object
class Person {
	constructor(firstname, lastname){
		this.firstname = firstname;
		this.lastname = lastname;
	}
	greet(){
		return ‘Hi’ + firstname;
  	}
}
//A js class define an object
var john = new Person(‘John’,’Doe’);
//Setting up prototype with classes
class InformalPerson extends Person {
	constructor(firstname, lastname){
		super(firstname,lastname);
	}
	greet(){
		return ‘Yo ’ + firstname;
  	}
}

Click me to learn more about - Inheritance

#BIGWORD Syntactic Sugar: A different way to Type something that doesn’t change how it works under the hood.


Subscribe

If you want a gist of the actual document, subscribe to the newsletter.


Bookmark

Unlike life, keyboards do have shortcuts, press COMMAND+D to make this an easily accessible resource by bookmarking it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment