Difference between revisions of "Javascript Object Oriented Programming"

From Logic Wiki
Jump to: navigation, search
(Created page with "Category:Javascript Category:OOP == 4 Pillars of OOP == * Encapsulation * Abstraction * Inheritance * Polymorphism <pre class="brush:js;"> // The simples...")
 
 
(2 intermediate revisions by the same user not shown)
Line 1: Line 1:
 
[[Category:Javascript]]
 
[[Category:Javascript]]
 
[[Category:OOP]]
 
[[Category:OOP]]
 +
 +
Cheat sheets from Mosh Hamedanis's Udemy Course
  
 
== 4 Pillars of OOP ==
 
== 4 Pillars of OOP ==
Line 8: Line 10:
 
* [[Polymorphism]]
 
* [[Polymorphism]]
  
 +
== Cheat Sheet ==
 +
The simplest way to create an object is using an object literal
 
<pre class="brush:js;">
 
<pre class="brush:js;">
// The simplest way to create an object is using an object literal
 
 
const circle = {  
 
const circle = {  
 
   radius: 1,  
 
   radius: 1,  
 
   draw: function() {}
 
   draw: function() {}
 
};  
 
};  
 
+
</pre> 
// To create multiple objects with the same structure and behaviuor (methods), use a factory or a constructor.  
+
To create multiple objects with the same structure and behaviuor (methods), use a factory or a constructor.  
 
+
==== Factory function ====
// Factory function  
+
<pre class="brush:js;">
 
function createCircle(radius) {  
 
function createCircle(radius) {  
 
   return {
 
   return {
Line 24: Line 27:
 
   }  
 
   }  
 
}  
 
}  
 
+
</pre>
// Constructor function  
+
==== Constructor function ====
 +
<pre class="brush:js;">
 
function Circle(radius) {  
 
function Circle(radius) {  
 
     this.radius = radius;  
 
     this.radius = radius;  
 
     this.draw = function() {}
 
     this.draw = function() {}
 
}  
 
}  
   
+
</pre>   
// Every object has a "constructor" property which returns the function that was used to construct or create that object.  
+
Every object has a "constructor" property which returns the function that was used to construct or create that object.  
 +
<pre class="brush:js;">
 
const x = {};
 
const x = {};
 
x.constructor; // returns Object()  
 
x.constructor; // returns Object()  
 
+
</pre> 
// In JavaScript, functions are objects. They have properties and methods.  
+
In JavaScript, functions are objects. They have properties and methods.  
 +
<pre class="brush:js;">
 
Circle.name;  
 
Circle.name;  
 
Circle.length;
 
Circle.length;
Line 41: Line 47:
 
Circle.call({}, 1); // to call the Circle function  
 
Circle.call({}, 1); // to call the Circle function  
 
Circle.apply({}, [1]);
 
Circle.apply({}, [1]);
 +
</pre>
 +
Value types are copied by their value, reference types are copied by their reference.
  
// Value types are copied by their value, reference types are copied by their reference.
+
'''Value types''' in JavaScript are: String, Number, Boolean, Symbol, undefined and null
// Value types in JavaScript are: String, Number, Boolean, Symbol, undefined and null
+
 
// Reference types are: Object, Function and Array  
+
'''Reference types''' are: Object, Function and Array  
 
    
 
    
// JavaScript objects are dynamic. You can add/remove properties:  
+
 
 +
JavaScript objects are dynamic. You can add/remove properties:  
 +
<pre class="brush:js;">
 
circle.location = {};
 
circle.location = {};
 
circle['location'] = {};
 
circle['location'] = {};
 
                        
 
                        
 
delete circle.location;  
 
delete circle.location;  
                     
+
</pre>                     
// To enumerate the members in an object:  
+
To enumerate the members in an object:  
 +
<pre class="brush:js;">
 
for (let key in circle) console.log(key, circle[key]);
 
for (let key in circle) console.log(key, circle[key]);
  
 
Object.keys(circle);  
 
Object.keys(circle);  
                     
+
</pre>                     
// To see if an object has a given property
+
To see if an object has a given property
 +
<pre class="brush:js;">
 
if ('location' in circle)
 
if ('location' in circle)
                     
+
</pre>                     
// Abstraction means hiding the complexity/details and showing only the essentials.
+
// We can hide the details by using private members. Replace "this" with "let".
+
  
 +
Abstraction means hiding the complexity/details and showing only the essentials.
 +
 +
We can hide the details by using private members. '''Replace "this" with "let".'''
 +
<pre class="brush:js;">
 
function Circle(radius) {  
 
function Circle(radius) {  
 
   // Public member  
 
   // Public member  
Line 70: Line 84:
 
   let defaultLocation = {};                       
 
   let defaultLocation = {};                       
 
}                       
 
}                       
 
+
</pre>
// To define a getter/setter, use Object.defineProperty():
+
To define a getter/setter, use Object.defineProperty():
 
+
<pre class="brush:js;">
 
Object.defineProperty(this, 'defaultLocation', {
 
Object.defineProperty(this, 'defaultLocation', {
 
     get: function() { return defaultLocation; },
 
     get: function() { return defaultLocation; },
Line 78: Line 92:
 
});
 
});
 
</pre>
 
</pre>
 +
 +
Every object (except the root object) has a prototype (parent).
 +
 +
To get the prototype of an object:
 +
<pre class="brush:js;">
 +
Object.getPrototypeOf(obj);
 +
</pre>
 +
 +
In Chrome, you can inspect "__proto__" property. But you should not use that in the code.
 +
 +
To get the attributes of a property:
 +
<pre class="brush:js;">
 +
Object.getOwnPropertyDescriptor(obj, 'propertyName');
 +
</pre>
 +
 +
To set the attributes for a property:
 +
<pre class="brush:js;">
 +
Object.defineProperty(obj, 'propertyName', {
 +
    configurable: false,    // cannot be deleted
 +
    writable: false,
 +
    enumerable: false
 +
});
 +
</pre>
 +
 +
Constructors have a "prototype" property. It returns the object that will be used as the prototype for objects created by the constructor.
 +
<pre class="brush:js;">
 +
Object.prototype === Object.getPrototypeOf({})
 +
Array.prototype === Object.getPrototypeOf([])
 +
</pre>
 +
 +
All objects created with the same constructor will have the same prototype.
 +
 +
A single instance of this prototype will be stored in the memory.
 +
<pre class="brush:js;">
 +
const x = {};
 +
const y = {};
 +
Object.getPrototypeOf(x) === Object.getPrototypeOf(y); // returns true
 +
</pre>
 +
 +
Any changes to the prototype will be immediately visible to all objects referencing this prototype.
 +
 +
When dealing with large number of objects, it's better to put their methods on their prototype. This way, a single instance of the methods will be in the memory.
 +
<pre class="brush:js;">
 +
Circle.prototype.draw = function() {}
 +
</pre>
 +
 +
To get the own/instance properties:
 +
<pre class="brush:js;">
 +
Object.keys(obj);
 +
</pre>
 +
 +
To get all the properties (own + prototype):
 +
<pre class="brush:js;">
 +
for (let key in obj) {}
 +
</pre>
 +
 +
=== Cloning an Object ===
 +
circle to another
 +
for (let key in circle)
 +
  another[key] = circle[key];
 +
or to clone one or more object to another
 +
const another = Object.assign({}, circle)
 +
to add other properties during cloning
 +
const another = Object.assign({color:"yellow"}, circle)
 +
with spread operator
 +
const another = {...circle}

Latest revision as of 09:27, 14 February 2021


Cheat sheets from Mosh Hamedanis's Udemy Course

4 Pillars of OOP

Cheat Sheet

The simplest way to create an object is using an object literal

const circle = { 
   radius: 1, 
   draw: function() {}
}; 

To create multiple objects with the same structure and behaviuor (methods), use a factory or a constructor.

Factory function

function createCircle(radius) { 
   return {
      radius, 
      draw: function() {}
   } 
} 

Constructor function

function Circle(radius) { 
    this.radius = radius; 
    this.draw = function() {}
} 

Every object has a "constructor" property which returns the function that was used to construct or create that object.

const x = {};
x.constructor; // returns Object() 

In JavaScript, functions are objects. They have properties and methods.

Circle.name; 
Circle.length;
Circle.constructor; // returns Function()
Circle.call({}, 1); // to call the Circle function 
Circle.apply({}, [1]);

Value types are copied by their value, reference types are copied by their reference.

Value types in JavaScript are: String, Number, Boolean, Symbol, undefined and null

Reference types are: Object, Function and Array


JavaScript objects are dynamic. You can add/remove properties:

circle.location = {};
circle['location'] = {};
                      
delete circle.location; 

To enumerate the members in an object:

for (let key in circle) console.log(key, circle[key]);

Object.keys(circle); 

To see if an object has a given property

if ('location' in circle)

Abstraction means hiding the complexity/details and showing only the essentials.

We can hide the details by using private members. Replace "this" with "let".

function Circle(radius) { 
   // Public member 
   this.radius = radius; 

   // Private member                       
   let defaultLocation = {};                      
}                       

To define a getter/setter, use Object.defineProperty():

Object.defineProperty(this, 'defaultLocation', {
    get: function() { return defaultLocation; },
    set: function(value) { defaultLocation = value; }
});

Every object (except the root object) has a prototype (parent).

To get the prototype of an object:

Object.getPrototypeOf(obj); 

In Chrome, you can inspect "__proto__" property. But you should not use that in the code.

To get the attributes of a property:

Object.getOwnPropertyDescriptor(obj, 'propertyName');

To set the attributes for a property:

Object.defineProperty(obj, 'propertyName', {
    configurable: false,    // cannot be deleted
    writable: false,
    enumerable: false
});

Constructors have a "prototype" property. It returns the object that will be used as the prototype for objects created by the constructor.

Object.prototype === Object.getPrototypeOf({})
Array.prototype === Object.getPrototypeOf([])

All objects created with the same constructor will have the same prototype.

A single instance of this prototype will be stored in the memory.

const x = {};
const y = {};
Object.getPrototypeOf(x) === Object.getPrototypeOf(y); // returns true 

Any changes to the prototype will be immediately visible to all objects referencing this prototype.

When dealing with large number of objects, it's better to put their methods on their prototype. This way, a single instance of the methods will be in the memory.

Circle.prototype.draw = function() {}

To get the own/instance properties:

Object.keys(obj);

To get all the properties (own + prototype):

for (let key in obj) {}

Cloning an Object

circle to another

for (let key in circle)
  another[key] = circle[key];

or to clone one or more object to another

const another = Object.assign({}, circle)

to add other properties during cloning

const another = Object.assign({color:"yellow"}, circle)

with spread operator

const another = {...circle}