Writing in the front
Browse below I feel still want some foundation! Below involved too many knowledge points, basically every take out to write a few articles, I am in the process of writing an article just do simple implementation, I’m just provides a train of thought, more details still need to study, the article content are many, hard work, if there are other views or opinions, welcome advice, the final paper will sleep shallow, know this matter to practise
Relationships between functions and objects in JavScript
Everything in JavScript is an object, but outside of the basic types, functions are objects, and objects are created from functions, which leads to my discussion of both kinds of programming. The following is a simple description of the type judgment and prototype, which is not the key point here. There is no specific description. If you are interested, you can search Baidu/Google.
// Type judgment
// Basic type
console.log(typeof 1) // | ==> number
console.log(typeof '2') // | ==> string
console.log(typeof undefined) // | ==> undfined
// The null type is null.
console.log(typeof null) // | ==> object
console.log(Object.prototype.toString.call(null)) // | ==> [object Null]
TypeError: right-hand side of' instanceof' is not an object
console.log(null instanceof null)
console.log(typeof Symbol()) / / | = = > symbol new type 】 【 ES6
console.log(typeof false) // | ==> boolean
console.log(typeof BigInt(9007199254740991n)) / / | = = > bigint "new type"
// Reference type - object
console.log(typeof ((a)= > {})) // | ==> function
console.log((() = > {}) instanceof Object) // true
console.log(typeof []) // | ==> object
console.log(typeof {}) // | ==> object
console.log(typeof (/ /. /)) // | ==> object
console.log(typeof new Date()) // | ==> object
console.log(typeof new String()) // | ==> object
console.log(typeof new Number()) // | ==> object
Copy the code
// fn ====> function fn() {} // Object ====> function Object () {} // function ====> function Funtion() new fn() - __proto__ - | write left - fn -- -- -- -- -- -- -- -- -- -- - fn. Prototype -- -- -- -- -- -- -- -- __proto__ -- -- -- -- -- - > Object. The prototype -- __proto__ -- - > null | Write | -- -- -- -- -- -- -- -- -- __proto__. -- -- -- -- -- -- - > the Function prototype __proto__ -- -- - | write Function -- -- -- -- -- -- -- - > __proto__ | ObjectCopy the code
Object Oriented Programming (OOP)
The most common form of expression in object-oriented programming is class, which provides 3 major object-oriented features and 5 major principles on ️. There are many of these on the Internet. I just make a simple list and I will implement the features as follows. The principle is the specification of object-oriented programming, and the characteristic is the implementation of object-oriented programming, provided that you have carefully understood the following core concepts.
- The three major characteristics
- inheritance
- polymorphism
- encapsulation
- The five principles of
- Single [a class should have one and only one reason to change it, which means a class should only have one job]
- Open closed objects or entities should be open to extension, but closed to modification.
- Richter substitution [i.e., calls to the parent class also apply to the child class]
- Dependency inversion [High level modules should not depend on low level modules]
- Interface isolation [clients should not be forced to implement an interface they do not use, or clients should not be forced to rely on methods they do not use]
inheritance
Inheritance is an object oriented feature that allows subclasses to call property methods that they do not have.
/** ES6 **/
class Parent {}
class Child extends Parent { constructor () { super()}}/** ES5 **/
function parent () { this.run () {} }
parent.prototype.eat = function () {}
function child () {}
// Original type inheritance
child.prototype = parent.prototype
child.prototype.constructor = child
// Prototype chain inheritance
child.prototype = new parent()
child.prototype.constructor = child
// Constructor inheritance
function boyChild (..arg) { parent.apply(this, arg) }
// Composite inheritance
function boyChild (..arg) { parent.apply(this, arg) }
boyChild.prototype = new parent()
child.prototype.constructor = child
// Parasitic composite inheritance
function child (..arg) { parent.apply(this, arg) }
/ / ${1}
(
function () {
function transmit () {};
transmit.prototype = parent.prototype
child.prototype = new prototype()
child.prototype.constructor = child
}
)()
/ / ${2}
child.prototype = Object.create(parent.prototype)
/ /...
/ / summary
/ / inherited methods varied, nothing more than, is through, one way to do not belong to own property methods can be invoked, along the way and the copy of the prototype assignment can be summed up a variety of different ways of inheritance, the advantages and disadvantages of each way, is considered more, inherit the integrity of the properties of the method and the impact on the instantiation objects, For example, whether methods on the instance and methods on the stereotype chain can both be called or whether reference-passing changes the same stereotype chain.
Copy the code
/** * for instance pair inheritance **/
// Interfaces are not provided in ES6, but Typescript supports interfaces very well. Typescript is a superset of javascript and provides very good support for object orientation
// Typescript
// This is highly recommended. It avoids many low-level errors and provides type checking, especially for those who have written the Java front-end.
interface parent { run: (a)= > void }
class child implements parent { run () {} }
/ / after transcoding
var child = /** @class */ (function () {
function child() {
}
child.prototype.run = function () {};returnchild; } ());Copy the code
polymorphism
Polymorphism is one of the characteristics of object oriented, which can realize that subclasses have different pairs of representation, can realize the same form of representation, can have different pairs of states
/** ES6 **/
/ / ${1}
class Animal {
eat () { console.log('animal eat')}}class Pig extends Animal {
constructor () { super() }
eat () { console.log('pig eat grass')}}class Tiger extends Animal {
constructor () { super() }
eat () { console.log('tiger eat pig')}}${2}; ${2}
class Animal {
eat () {
if (typeof arg === ' ') {
console.log('operating one')}else if (typeof arg === ' ') {
console.log('operating two')}else {
console.log('operating three')}}}/** ES5 **/
// The idea is to go up the prototype chain and override the method by defining it in front of the superclass
/ / ${1}
function animal () { this.eat = function () { console.log('Animal eat')}}function pig () {
animal.call(this)
this.eat = function () { console.log('pig eat grass')}}function tiger () {
animal.call(this)
this.eat = function () { console.log('tiger eat pig')}}/ / ${2} overloading
function animal () {
eat () {
if (typeof arg === ' ') {
console.log('operating one')}else if (typeof arg === ' ') {
console.log('operating two')}else {
console.log('operating three')}}}Copy the code
encapsulation
Encapsulation is a feature of object orientation. It encapsulates properties and methods into an object. It can use private or public properties to provide methods or properties that can be accessed externally
/** ES6 **/ // ES6 does not provide true private methods and properties, Class constructor () {constructor ();} class constructor () {constructor ();}} this.height = '50' } get height() { return undefined } set height (value) { return undefined } } /** ES5 **/ const animal = (function (arg) { let height = 50 function eat () {console.log(height)} return { eat } })([]) /** Typescript **/ class Animal { public height: number private name: string protected color: string constructor (height: number, name: string, color: string) { this.height = height this.name = name this.color = color } private eat ():void { console.log(this.name) } }Copy the code
Functional Programming Programming (FP)
Functional programming advocates the function is first citizen “refers to the function and other data types, on an equal position, can be assigned to other variables, can also be used as a parameter, to another function, or as other function return values, purely functional programming, is a pure function 【 if incoming parameters are the same, will return the same result, Independent of external data state [example below], functional programming features
/ / pure functions
const add = (one, two) = > { return one + two }
// Impure function
let two = 1
const add = (one) = > { return one + two }
Copy the code
- Closures and higher-order functions
- Currie,
- Partial function
- Assembly and piping
- functor
Closures and higher-order functions
There are other functions inside the closure understanding function that allow the data state of the parent function to be stored. The higher-order understanding function can be passed to other functions through variables
// Implement a higher-order map function that can only be called once
const map = (fn) = > {
let once = false
return (arr) = > { return once? null: (once = true, arr.map(fn)) }
}
const fn = (item) = > item + 10
const arrMap = map(fn)
arrMap([1.2.3]) / / [11, 12, 13]
arrMap([4.5.6]) // null
Copy the code
Currie,
Currying is the process of converting a function of several variables into a nested function of one
function curry (fn) {
returncurryN (... arg) {if (arguments.length < fn.length) {
return function () {
return curryN.call(null. arg.concat(... arguments)) } }return fn.call(null. arguments) } }const add = curry ((x, y, z) = > x + y + z)
console.log(add(2) (3) (4)) / / 9
Copy the code
Partial function
Partial functions understand that initialization specifies some of the parameters of the original function and creates a new function that accepts the remaining parameters
function proto(fn, ... pagram) {
return (. args) = > {
args.forEach((item, index) = > { if(item && ! pagram[index]) pagram[index] = item })return fn.apply(null, pagram)
}
}
let add = proto((x, y) = > { console.log(x + y) }, undefined.10)
add(2) / / 12
Copy the code
Assembly and piping
Combinatorial and piped understanding takes the output of one function as the input of another, flowing left to right or right to left from a queue of functions like water
// Single parameter, simple combination
const compose = (fn, fnc) = > (arg) => fn(fnc(arg))
// Multiple parameters, using the partial function
function mapArr(arr, fn) { return arr.map(fn) }
function filte (arr, fn) { return arr.filter(fn) }
let map = proto(mapArr, undefined, (item) => { return item + 10 })
let filter = proto(filte, undefined, (item) => { return item })
let mapFilter = compose(map, filter)
console.log(mapFilter([1.false.9.4])) / / [11, 19, 14]
// Multiple function combinations
const reduce = (arr, fn, value) = > {
let initValue = value? value: arr[0]
arr.forEach((item) = > { initValue += fn(initValue, item) })
return initValue
}
const compose = (. arg) = > (value) => reduce(arg.reverse(), (acc, fn) => fn(acc), value)
let add = compose((a)= > { return 1= > {}, ()return 2= > {}, ()return 3 })
add(6) / / 12
Copy the code
functor
Definition of a functor A functor is a normal object (in other languages, it might be a class) that implements the map function, which generates a new object as it traverses the value of each object. In simple terms, a functor is a container that holds the value. Hi, hard to read. Code up.
- Figure [Stolen on the Internet]
// Implement a basic defined functor that satisfies the definition
// Implement the map method to generate a new object as we iterate over it
function container (value) { this.value = value }
container.prototype.of = function (value) { return new container(value) }
container.prototype.map = function(fn) { return new container().of(fn(this.value)) }
new container().of([1.5.7.3]).map((arr) = > { return arr.filter((item) = > item === 5)})
console.log(
new container().of([1.5]).map((arr) = > { return arr.filter((item) = > item === 5)}).value
) / / 5
Copy the code
Write in the last
At this point the basic idea of object-oriented and functional programming is simple to achieve, more need to learn
The above two kinds of programming methods have provided me with a lot of ideas for solving problems and organizing code framework during the process of learning and practice, and I can also see the shadow of their implementation in many open source libraries. Of course, it is not easy to really understand these two kinds of programming methods. More importantly, I need to continuously practice, think and summarize, and gradually accumulate. Finally, you are welcome to my Blog, where I tend to write an original article every week
- Blog