Object.setPrototypeOf() Method JavaScript

There are two camps in JavaScript, one who uses function constructors to create objects and one who directly uses object literals. In JavaScript, function constructors can be extended by using the Object.create() method. This method lets you set prototype of one object to another object.

Constructor2.prototype = Object.create(Constructor1.prototype);

Extending Object Literals

Object literals don’t have prototype property. So, if you want to inherit properties of one literal to another, you can do it several ways. Prior to ES2015, you had to write your own extend method that would copy methods from one object to another. ES2015 introduced few new methods that makes this process easier. The setPrototypeOf() method is one of such methods.

Syntax

Object.setPrototypeOf(targetObj, sourceObj);

Here, targetObj is what you are setting prototype to from sourceObj. This method essentially sets a reference to sourceObj’s methods to targetObj’s __proto__. To understand the utility of this, let’s take two objects, toyota and camry. toyota has a drive() method. Setting the camry’s prototype to toyota makes toyota’s drive() method automatically available to camry. This is done by setting its reference in camry’s __proto__ property.


let toyota = {
  drive() {
    return 'driving toyota';
  }
}

let camry = {
  wifi() {
    return 'using wifi';
  }
}

// Set toyota's __proto__ to camry's  __proto__'s  __proto__
Object.setPrototypeOf(camry, toyota);

console.dir(camry); //prints the camry object
console.log(camry.wifi()); // using wifi
console.log(camry.drive()); // driving toyota

Object.setPrototypeOf()

If you inspect the camry object, you can view the __proto__ property and the reference to the drive() method of toyota. Since the setPrototypeOf() method sets a reference, any changes to toyota’s properties is automatically accessible to camry.

let toyota = {
  drive() {
    return 'driving toyota';
  }
};

let camry = {
  wifi() {
    return 'camry';
  }
};

// Set toyota's __proto__ to camry's  __proto__'s  __proto__
Object.setPrototypeOf(camry, toyota);

// Add a new Method to toyota object
toyota.newMethod = function() {
  return 'new method from toyota';
};

console.log(camry.newMethod()); // Prints 'new method from toyota' 



If you have a method with the same name in both the targetObject and the SourceObject, the method in the targetObject would have higher precedence. This is because javaScript first looks for object’s own method before looking into it’s prototype.

let toyota = {
  drive() {
    return 'driving toyota';
  }
}

let camry = {
  drive() {
   return 'driving camry';
  }
}

Object.setPrototypeOf(camry, toyota);
console.dir(camry.drive()); // logs "driving camry"

Super keyword

You can call the method of the sourceObject from the targetObject’s method by using the super keyword.

let toyota = {
  drive() {
    return 'driving toyota';
  }
}

let camry = {
  drive() {
   return `${super.drive()} camry`;
  }
}

Object.setPrototypeOf(camry, toyota);
console.dir(camry.drive()); // logs "driving toyota camry"

Avoid setting __proto__ manually

Prior to ES2015, Object.prototype.__proto__ was used to set the prototype of object literals. You can still use it as shown in the below example. However, it’s not recommended.

let toyota = {
  print() {
    return 'toyota';
  }
}

let camry = {
  printMe() {
    return 'camry';
  }
}

camry.__proto__ = toyota;

console.dir(camry.print());

Object.create method JavaScript

In JavaScript, Prototype inheritance is much easier than you would have imagined. Simply understand the fundamentals, like we always do!

Inheritance in JavaScript is prototype-based. Every constructor has a property called prototype. For more information about the basics of prototypes, click here.

Master constructor object ‘Object’

Object is the master constructor in JavaScript. Don’t forget to take a note of the capitalization of letter ‘O’ in Object. It’s a
function constructor. Directly or indirectly, every object is created by using Object (master object). Since, it is available in the global space, you can access it directly. If you console.dir(Object), you can view all methods that are available to Object. One of the methods is create(). It enables prototypal inheritance in JavaScript.

console.dir(Object);

Object.create Method

Syntax

Object.create(prototypeObject, propertiesObject);

The Object.create method takes two arguments. First argument must be either an object or null. The second argument is optional and used to set properties. These properties are set in object’s prototype.

Creating Objects

const myObject = Object.create(Object.prototype);
console.dir(myObject);

In the above example, the myObject object is created by using Object’s prototype. This means myObject’s creator is Object.prototype. If you inspect myObject, you can view the following:
Inspecting Object
myObject does not contain anything. However, its __proto__ property is a reference to the Object’s prototype. Hence, you can call methods on myObject that are available in Object’s prototype. If you create an object literal by using const myLiteral = {};, it possesses the same __proto__ because internally every object’s __proto__ is set to Object.prototype.To create an object without setting its __proto__ reference to Object.prototype, pass null as an argument. To verify this, inspect the object. As shown in the image below, it does not contain __proto__ property.

const myObject = Object.create(null);
console.dir(myObject);

Object.create(null)

The Object.create() method also creates objects from constructors. It is similar to using the new keyword. The only difference is that by using the new keyword, you can run the constructor. Hence, it will set the initial properties in the constructor. Whereas, the Object.create() method doesn’t run the constructor and hence the initial properties are not set.

const Car = function(color) {
  this.color = color;
};

let car1 = new Car('red');
let car2 = Object.create(Car.prototype);

console.dir(car1);
console.dir(car2);

New vs Object.create

Extending a Constructor

The main use of the Object.create() method is to extend the constructor. This means that you can inherit methods from a constructor’s prototype properties to other constructors. To extend a constructor, set a prototype reference of one object to another by using the Object.create() method.
Note: Only the constructor’s prototype is inherited and not the constructor.

const Car = function(color) {
  this.color = color;
};

Car.prototype.getColor = function() {
  return this.color;
}

const ToyCar = function() {};

ToyCar.prototype = Object.create(Car.prototype);

const legoCar = new ToyCar();

console.log(legoCar);

Object.create



Verifying Prototype

In the above example, ToyCar’s __proto__ is set to Car and Car’s __proto__ is set to Object. The isPrototypeOf method verifies if legoCar, which is originally created by using the ToyCar constructor, is a prototype of ToyCar, Car and Object. The instanceof operator also performs the similar task.

const Car = function() {};
const ToyCar = function() {};

ToyCar.prototype = Object.create(Car.prototype);

const legoCar = new ToyCar();

// Using the isPrototypeOf method
console.log(ToyCar.prototype.isPrototypeOf(legoCar)); //true
console.log(Car.prototype.isPrototypeOf(legoCar)); //true
console.log(Object.prototype.isPrototypeOf(legoCar)); //true

// Using the instanceof operator
console.log(legoCar instanceof ToyCar); //true
console.log(legoCar instanceof Car); //true
console.log(legoCar instanceof Object); //true

Conclusion

In the classical inheritance, you can create a subClass from a superClass. The subClass inherits all methods of the superClass. In JavaScript, a subConstructor inherits all methods from a superConstructor by using the Object.create method. Contrary to the classical inheritance, where methods of superClass are copied to subClass, JavaScript uses a prototype reference to access methods from the superConstructor.

JavaScript Prototype Explained

Every constructor function has a property called prototype. You can add properties and methods to it. Using a constructor function, When you create a new object, the object has access to prototype methods.

Sample code:

let Car = function(color) {
 this.color = color;
};

Car.prototype.getColor = function() {
 return this.color;
};

let redCar = new Car('red');

console.dir(redCar);

If you inspect the redCar object, you will see the following.Inspect ObjectIn the above image, the getColor() is not a part of the redCar object. There is another property called __proto__, which is set automatically. You can think of __proto__ as the creator of redCar. If you expand __proto__, the getColor method and the constructor are displayed. Constructor is the a reference to the Car Constructor that created redCar.
__proto__ property If you expand the Car constructor, the prototype property of the constructor is displayed. If you further expand the prototype property, the getColor method is displayed.

ProtoType Property JavaScriptThe getColor method from __proto__ is actually a reference to the one you added to the constructor’s prototype. It looks tricky, however, all you care about is that __proto__, the creator of redCar, has the getColor method. Hence, when you call the redCar.getColor() method, JavaScript will look inside the redCar object. If the method doesn’t exist in the object, it will look for the method in the object’s creator, which is __proto__. It will find it and execute it.
JavaScript Master ObjectSo, let’s analyze a little more and discover how is __proto__ created. If you further expand __proto__, you will see its creator, which is the master __proto__. This is basically a master object called Object (the letter ‘O’ is capitalized). Every object in JavaScript is created from Object. It also has some methods. One of the methods is toString(). When you call this method on redCar, JavaScript will first search for this method in the redCar object. If it can’t find it there, it keeps searching for the method all the way to the end of the prototype chain.




There are pros and cons of using prototype inheritance. The best part is, the inheritance makes objects lighter. The drawback is that every time you call a method that is not a part of the object, it looks for the method up the prototype chain. Hence, it makes it a little slower. The workaround is, if you are going to call this method frequently, store it in a variable to avoid the lookup.

let toString = Object.toString;
console.log(redCar.toString());

Overwriting Object Methods

If you want to customize the toString() method, you can add it to the object’s prototype. However, there are times when you want to make method available to every object. In such case, add it to the master object’s prototype. This would shadow the native toString() method.

Object.prototype.toString = function(){
    return `color:${this.color}`;
};

let Car = function(color) {
  this.color = color;
};

Car.prototype.getColor = function() {
  return color;
};

let redCar = new Car('red');


console.dir(redCar.toString());

In next article, I will show you how to use Object.create() method to set prototype of one object to another. Follow the link below. Object.create() method

JavaScript Function Constructors

It is very important to understand how JavaScript function constructors work before we move to higher level topics of Object Oriented JavaScript. In this article, I am not going to explain about the JavaScript class constructor. Instead, I’ll explain about ‘function’ constructors.
The ultimate objective of Object Orient Programming is to create objects with ease. Languages like Java have classes and each class can have a constructor, and its job is to set initial properties of the object. In JavaScript, you can create an object by directly using constructors. JavaScript lets you use a function as a constructor, if called in a specific way. And, that’s what this entire article is all about!

Usually, the job of a function is to run a specific job. Let’s say, I want to add two numbers. will write a function that takes two arguments and return the addition of the two numbers.

Sample of a function for adding two numbers:

let add = function(number1, number2) {
 return number1 + number2;
};

let sum = add(1, 2);

Now, let’s look at an example of a function constructor.

let Car = function(color) {
 this.color = color;
};

let redCar = new Car('red');

As shown in the above example, a regular function takes arguments. It performs an action within the body of the function and returns the result. A regular function may or may not return anything.
Function constructor, on the other hand, accepts color as an argument and sets it to its this.The constructor function does not contain a return statement. Instead, it returns a new object with the property that is passed as an argument.

The basic syntax difference for executing a regular function and a constructor function is the usage of the new keyword.

If you were to manually create an object without using the constructor function, the syntax will look like following:

let redCar = {
 color: 'red'
};

If you inspect the newly created object in a browser, this is how it would look like:


JavaScript function constructor inspect

As you can notice, it has a color property which is set to ‘red’; The property, __proto__, is its creator. If you expand the __proto__, you will see the following:

JavaScript function constructor inspect

The reference to the constructor that set the initial property is the Car constructor that you used to create redCar.

Drawbacks of not using new

Now, let’s consider a scenario where you execute a constructor function as a regular function without using the keyword ‘new’.

let Car = function(color) {
  this.color = color;
};

let redCar = Car('red');

In this case, this.color = color will create a new property color in the global space. You can verify the result by using console.log(window.color);

To prevent such error, add se use strict, which throws the following exception:

error calling function constructor without 'new' keyword

You can also use the new.target to throw a customized error message..

let Car = function(color) {
  if (!new.target) throw 'Car() must be called with new';
  this.color = color;
};

let redCar = new Car('red');

Private Vs Public properties

In JavaScript, all object properties are public, which means you can access it directly. For example, redCar.color. JavaScript does not have a native support for private property. Private properties are the properties you cannot access directly by using a dot notation. However, you can call a getter or have a getter method like getColor to access it and use closure.

let Car = function(_color) {
  this.setColor = function(color){
    _color = color;
  }
  this.getColor = function() {
    return _color;
  };
};

let redCar = new Car('red');

console.log(redColor.getColor());

Here _color is a private variable that cannot be accessed by the object using redCar._color.
Since it is a closure, the methods have access to them.

Adding methods to a Constructor

Best way to have methods is to set methods in prototype space. For more information about settings methods in the prototype space, go to Prototype.

Sass CSS Tutorial for beginners

Sass stands for  Syntactically Awesome Stylesheet

File extension for a Sass file is “.scss”,  which stands for Sassy CSS. “.sass” is also a valid extension for Sass with bit concise syntax.  In this article, we will only look at the latest version which is SCSS.

Why Sass?

Sass is a preprocessor that gives you a little better way of writing styles where you can have features such as nesting that are missing from CSS. In nutshell, you can write a sort of object-oriented styles by using Sass. Sass compiler converts “.scss” files to “.css” files. Since you do not need to edit CSS files directly,  you can avoid some of the mess that CSS files may create.

Code Example

[Look at the SCSS example below. Click the SCSS tab to see the SCSS code, and then from the lower-right, click View Compiled. This way, you can toggle between SCSS and compiled CSS]

The following SCSS has an ID called main, and within that there are two nested elements a and h2.  When you click View Compiled, it produces CSS that creates a style for each element. This is a basic example of how SCSS works. You can modify the example and check the result in the Result tab.


See the Pen Flat minion by Hemil Patel (@codepatel) on CodePen
1

Comments

There is a need for writing Sass specific comments that describes some of the rationals which is called Sass comments. When Sass compiler compiles down to normal CSS, the comments mentioned in Sass do not carryover to CSS.

Sass  comment :   // This is Sass Comment [Note: This is not valid in CSS]

CSS comment :  /* This is CSS Comment with opening and closing */


See the Pen Flat minion by Hemil Patel (@codepatel) on CodePen
1

Variables

Variables are very useful features of Sass.  For example, you can define a variable for a color and use it for various styles. The advantage is that when you have to replace a color with a new color, you do not need to change the color throughout the style. You only make a change to the variable value. To define a variable, add a prefix $.  See the example below.

$hcolor = red;

h2{

color: $hcolor;

}


See the Pen Flat minion by Hemil Patel (@codepatel) on CodePen
1

CSS align elements horizontally center

CSS align elements horizontally center

Let’s understand what we are trying to do here. We want to center an element horizontally within the parent element so that we would have an element placed at an equal distance from either sides.

CSS ALIGN HORIZONTALLY

There are two different ways we can align an element. The option depends on the display property of the element you are trying to place.

  • Center the element by using its own CSS – display:block;
  • Center the element by using parent element’s CSS – display:inline*
    *display:inline, display:inline-block; display-inline-flex;

1) Blocks

css block element
css block element

Elements with “display:block” property are blocks. When no width is specified, blocks occupy the entire width of the parent. In such case, there is no need to center these elements. When the width is specified, blocks would left align, by default.  You can center them by setting the left and right margins left to auto, respectively. In this case, you are adding style to the element and not the parent container. See the example below:

 


See the Pen Flat minion by Hemil Patel (@codepatel) on CodePen
1

2) Inline-* elements

css inline element
css inline element

Elements with”display:inline”, “display:inline-block”, and “display:inline-flex”,  property are the inline elements. Since, you have multiple inline elements within the same row, the horizontal centering has to be done from the parent container and not by the element itself. This is done by adding style “text-align:center” to the parent container. See the example below:


See the Pen Flat minion by Hemil Patel (@codepatel) on CodePen
1

[contact-form-7 id=”69″ title=”Contact form 1″]

Introduction to css

Introduction to css ( Cascading Stylesheet )

In webpage development, the inline style lines are responsible for formatting HTML elements.

For example in last tutorial we looked at the example Make me italic

[code language=”HTML”]<i>Make me italic</i>[/code]

Here the tag converts its content to Italic font.

Inline Styling

You can also stylize text this way using style attribute:

[code language=”HTML”]<p style=“text-formate:italic”>Make me Italic </i>[/code]

Output: Make me Italic

This works well however, it is usually not good practice to use formatting directly in the HTML file.

For example let’s say you also want the color of the text to be red

[code language=”HTML”]<p style=“text-formate:italic;color:red;”>Make me Italic </p>[/code]

Output: Make me Italic

More styles like making the text bold can be done this way:

[code language=”HTML”]<p style=“text-formate:italic;color:red;font-weight:bold”>Make me Italic </p>[/code]

Output: Make me Italic

It may not be conducive to have that many lines of style written into your HTML. It soon becomes illegible. This is alright if you can manage it, but there are other ways to make this less of an issue.

For example if you have three paragraphs and they all have the same style you can do the following:

[code language=”HTML”]
<p style=“text-formate:italic;color:red;font-weight:bold”>Paragraph 1 </p>
<p style=“text-formate:italic;color:red;font-weight:bold”>Paragraph 2</p>
<p style=“text-formate:italic;color:red;font-weight:bold”>Paragraph 3 </p>
[/code]

As you can see using style the attribute you have to repeat the same style three times. What’s worse is when you have 100 paragraphs where you want to apply the same style. Now, imagine you do all the work by adding the style to each paragraph as above and your boss ask you to change the font from italic to normal. This is where CSS comes to rescue!

Instead of writing inline style for each element move the style to a separate file with extension (.CSS)

intro to css3
html and css link reference

In HTML you can use tag-name or you will have to provide an attribute hook such as “id” or “class” and in the CSS you would refer to the hook to style that element. In the example below you can see the paragraph element has an attribute hook id with value “thisP” and in CSS using that hook you can color the font red. # (Pound sign) is called a css selector for id. In the next post we will discuss css selectors in detail.

HTML file ( Only showing what goes within body tag) :

[code language=”HTML”]
<p id=“thisP”> Using CSS<p>
[/code]

CSS file :

[code language=”CSS”]
#thisP{
color:red;
}
[/code]

Output:
Using CSS

 

 

[embedplusvideo height=”360″ width=”640″ editlink=”http://bit.ly/1qR8jZ6″ standard=”http://www.youtube.com/v/o1GdsNVYDHA?fs=1″ vars=”ytid=o1GdsNVYDHA&width=640&height=360&start=&stop=&rs=w&hd=0&autoplay=1&react=1&chapters=&notes=” id=”ep1903″ /]