markdown MEDIUM BLOG POST - Javascript的3个主要范例:面向对象编程的三个原则[第2部分,共4部分]

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown MEDIUM BLOG POST - Javascript的3个主要范例:面向对象编程的三个原则[第2部分,共4部分]相关的知识,希望对你有一定的参考价值。

# Javascript Paradigms
## 1. Object Oriented Programming (OOP) Paradigms
<details><summary><b> What is OOP?   </b></summary><hr>

## What?
Object Oriented Programming (OOP) refers to using self-contained pieces of code to develop applications. We call these self-contained pieces of code objects, better known as Classes in most OOP programming languages and Functions in JavaScript. 


**
Objects** can be thought of as the main actors in an application, or simply the main “things” or building blocks that do all the work. As you know by now, objects are everywhere in JavaScript since every component in JavaScript is an Object, including Functions, Strings, and Numbers. 
### Why?
### How?
Through **object literals** (Encapsulation)
```jsx
var myObj = {name: "Richard", profession: "Developer"};
```
or **constructor functions**  (Inheritance)

```jsx

  function Employee () {}

  
   Employee.prototype.firstName = "Abhijit";
   Employee.prototype.lastName = "Patel";
   Employee.prototype.startDate = new Date();
   Employee.prototype.signedNDA = true;
   Employee.prototype.fullName = function () {
   console.log (this.firstName + " " + this.lastName);
   };
  | ​
   ​var abhijit = new Employee () //​
   console.log(abhijit.fullName()); // Abhijit Patel​
   console.log(abhijit.signedNDA); // true
```
 to create objects in the OOP design pattern

<hr></details>


The **Three tenets** of  Object Oriented Programming (OOP):




<details><summary><b>1. Inheritance </b></summary><hr>

### The Best Inheritance Pattern

 Parasitic Combination Inheritance

## What?
 Inheritance (objects can inherit features from other objects)

**Inheritance** refers to an object being able to inherit methods and properties from a parent object (a Class in other OOP languages, or a Function in JavaScript).
### Why?
Lets say we have a quiz application to make different types of Questions. We will implement a MultipleChoiceQuestion function and a DragDropQuestion function. To implement these, it would not make sense to put the properties and methods outlined above (that all questions will use) inside the MultipleChoiceQuestion and DragDropQuestion functions separately, repeating the same code. This would be redundant.

Instead, we will leave those properties and methods (that all questions will use) inside the Question object and make the MultipleChoiceQuestion and DragDropQuestion functions inherit those methods and properties. 

**This is where inheritance is important**: we can reuse code throughout our application effectively and better maintain our code.

### How?


An instance is an implementation of a Function. In simple terms, it is a copy (or “child”) of a Function or object. For example:
```jsx
// Tree is a constructor function because we will use new keyword to invoke it.​
   ​function Tree (typeOfTree) {}
   ​
   ​// bananaTree is an instance of Tree.​
  ​var bananaTree = new Tree ("banana");
```
In the preceding example, bananaTree is an object that was created from the Tree constructor function. We say that the bananaTree object is an instance of the Tree object. Tree is both an object and a function, because functions are objects in JavaScript. bananaTree can have its own methods and properties and inherit methods and properties from the Tree object, as we will discuss in detail when we study inheritance below.


**using the Parasitic Combination Inheritance** 
Using the ***Object.create() Method**

```jsx
 if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {
        }
​
        F.prototype = o;
        return new F();
    };
}
```

Let’s quickly understand it is doing.

```jsx
Object.create = function (o) {
​//It creates a temporary constructor F()​
        function F() {
        }
​//And set the prototype of the this constructor to the parametric (passed-in) o object​
​//so that the F() constructor now inherits all the properties and methods of o​
        F.prototype = o;
​
​//Then it returns a new, empty object (an instance of F())​
​//Note that this instance of F inherits from the passed-in (parametric object) o object. ​
​//Or you can say it copied all of the o object's properties and methods​
        return new F();
    }
```

<hr></details>









<details><summary><b>2. Encapsulation   </b></summary><hr>





## What?
Encapsulation (each object is responsible for specific tasks).


### The Best Object Creation Pattern:

Combination Constructor/Prototype Pattern

Encapsulation refers to enclosing all the functionalities of an object within that object so that the object’s internal workings (its methods and properties) are hidden from the rest of the application. 

### Why?
This allows us to abstract or localize specific set of functionalities on objects.

### How?
To implement encapsulation in JavaScript, we have to define the core methods and properties on that object. To do this, we will use the best pattern for encapsulation in JavaScript: the Combination Constructor/Prototype Pattern. 
```jsx
function User (theName, theEmail) {
    this.name = theName;
    this.email = theEmail;
    this.quizScores = [];
    this.currentScore = 0;
}
​
User.prototype = {
    constructor: User,
    saveScore:function (theScoreToAdd)  {
        this.quizScores.push(theScoreToAdd)
    },
    showNameAndScores:function ()  {
        var scores = this.quizScores.length > 0 ? this.quizScores.join(",") : "No Scores Yet";
        return this.name + " Scores: " + scores;
    },
    changeEmail:function (newEmail)  {
        this.email = newEmail;
        return "New Email Saved: " + this.email;
    }
} 
```
### When? 
when you want to create objects with similar functionalities (to use the same methods and properties), you encapsulate the main functionalities in a Function and you use that Function’s constructor to create the objects. This is the essence of encapsulation. And it is this need for encapsulation that we are concerned with and why we are using the Combination Constructor/Prototype Pattern.

<hr></details>




<details><summary><b>3. Polymorphism</b></summary><hr>
### What?
Polymorphism (objects can share the same interface—how they are accessed and used—while their underlying implementation of the interface may differ)

 **In JavaScript it is a bit more difficult to see the effects of polymorphism** because the more classical types of polymorphism are more evident in statically-typed systems, whereas JavaScript has a dynamic type system.



### Why?

Polymorphism foster many good attributes in software, among other things it fosters modularity and reusability and make the type system more flexible and malleable

### How?

This is not simple to answer, different languages have different ways to implement it. In the case of JavaScript, as mentioned above, you will see it materialize in the form of type hierarchies using prototypal inheritance and you can also exploit it using duck typing.


What is polymorphism in Javascript? - https://stackoverflow.com/questions/27642239/what-is-polymorphism-in-javascript
<hr></details>

### OOP key words
Encapsulation - `object literals` 
Inheritance - `constructor functions` and  `new keyword`

以上是关于markdown MEDIUM BLOG POST - Javascript的3个主要范例:面向对象编程的三个原则[第2部分,共4部分]的主要内容,如果未能解决你的问题,请参考以下文章

Markdown

markdown编辑器中添加空格

markdown jx-troubleshooting_medium.md

markdown https://medium.com/@porteneuve/mastering-git-submodules-34c65e940407

bWAPP闯关系列(搭建+HTML Injection)~

工具学习_MarkDown