Read the article of big brother Yu

The devil Nezha 2021-05-04 18:21:45
read article big brother yu


By the way :Github source : | Seeking stars | welcome star, Encourage the author .

Hope to be able to help more small partners . Add me to exchange questions ( Not a big man , learn from each other , Create a good learning environment ). Which of the following do you not understand ?

  • What don't you understand , We can comment and communicate below

image.png

7cb7de90-8f72-11ea-82a0-b5001424c6ad_76030cd8-ab7c-40e8-bd10-475b50820298_thumb.jpg

Extended object capabilities

image.png

  • Object category

image.png

Name a function as createPerson() , It creates an object :

function createPerson(name, age) {
return {
name: name,
age: age
};
}
 Copy code 

When an attribute name of an object is the same as the local variable name ,ES6:

function createPerson(name, age) {
return {
name,
age
},
}
 Copy code 

When an attribute in an object literal has only a name , JS The engine looks for variables with the same name in the surrounding scope . If you find , The variable The value of will be assigned to the property of the same name of the literal quantity of the object .

es5 How to write it :

var person = {
name: 'jeskson',
sayName: function() {
console.log(this.name);
}
};
 Copy code 

es6 How to write it :

var person = {
name: 'jeskson',
sayName() {
console.log(this.name);
}
};
 Copy code 
  • The name of the property to be evaluated

Example :

var person = {},
lastName = "last name";
person["first name"] = "da1";
person[lastName] = "da2";
console.log(person["first name"]); // da1
console.log(person[lastName]); // da2
 Copy code 

In the example, two property names contain spaces , You can't use decimal notation to refer to them , The square bracket notation allows arbitrary strings to be used as property names .

Example optimization :

var person = {
"first name": "jeskson"
};
console.log(person["first name"]); // jeskson
 Copy code 
var lastName = "last name";
var person = {
"first name": "da1",
[lastName]: "da2"
};
console.log(person["first name"]); // "da1"
console.log(person[lastName]); // "da2"
 Copy code 

The square brackets inside the literal value of the object indicate that the property name needs to be evaluated , The result is a string

Example :

var da = " name";
var pserson = {
["first + da ]: "da1",
["last" + da ]: "da2"
};
console.log(person["first name"]); // "da1"
console.log(person["last name"]); // "da2"
 Copy code 
  • Equality operator ( == ) Or strictly equal operators ( === )
  • ES6: Object.is(), return true, It is required that they have the same type and the same value

Example :

console.log(+0 == -0); // true
console.log(+0 === -0); // true
console.log(Object.is(+0, -0)); // false
console.log(NaN == NaN); // false
console.log(NaN === NaN); // false
console.log(Object.is(NaN, NaN)); // true
console.log(5 == 5); // true
console.log(5 == "5"); // true
console.log(5 === 5); // true
console.log(5 === "5"); // false
console.log(Object.is(5, 5)); // true
console.log(Object.is(5, "5")); // false
 Copy code 

image.png

  • Object.assign() Method

Mix in ( Mixin ) Is in JS The most popular pattern for combining objects in .

A shallow copy , When the property value is an object , Copy only its references

function mixin(receiver, supplier) {
Object.keys(supplier).forEach(function(key) {
receiver[key] = supplier[key];
});
return receiver;
}
 Copy code 

Object.assign() Method , The method Accept a receiver , And any number of suppliers , And will return to the recipient .

Example :

"use strict";
var person = {
name: "da1",
name: "da2" // stay ES6 There is no error in strict mode
};
console.log(person.name); // "da2"
 Copy code 

Enumeration order of self owned properties

image.png

Modify the prototype of the object

  1. Object.getPrototypeOf() Method to get its prototype from any specified object
  2. Object.setPrototypeOf() Method to modify the prototype of any specified object

Example :

let person = {
getGreeting() {
return "hello";
}
};
let dog = {
getGreeting() {
return "hai";
}
};
let friend = Object.create(person);
console.log(friend.getGreeting()); // "hello"
console.log(Object.getPrototypeOf(friend) === person); // true
Object.setPrototypeOf(friend, dog);
console.log(friend.getGreeting()); // "hai"
console.log(Object.getPrototypeOf(friend) === dog); // true
 Copy code 

Use super Simple prototype access for reference

  • Object.getPrototypeOf() Method ensures that the correct prototype can be called , And a string is appended to the returned result .

Example :

let person = {
getGreeting() {
return "hello"
}
};
let dog = {
getGreeting() {
return "woof";
}
};
let friend = {
getGreeting() {
return Object.getPrototypeOf(this).getGreeting.call(this) + ", hi!";
}
};
Object.setPrototypeOf(friend, person);
console.log(friend.getGreeting()); // "hello hi!"
console.log(Object.getPrototypeOf(frined) === person); // true
Object.setPrototypeOf(friend,dog);
console.log(friend,getGreeting()); // "woof, hi!"
console.log(Object.getPrototypeOf(friend) === dog); // true
 Copy code 
  • call(this), It ensures that the internal this value

super Is a pointer to the prototype of the current object

Example :

let friend = {
getGreeting() {
// Object.getPrototypeOf(this).getGreeting.call(this)
return super.getGreeting() + ", hi!";
}
}
 Copy code 

Use ES6 Of super, Example :

let person = {
getGreeting() {
return "hello";
}
};
let friend = {
getGreeting() {
return super.getGreeting() + ", hi!";
};
Object.setPrototypeOf(friend, person);
let relative = Object.create(friend);
console.log(person.getGreeting()); // "hello"
console.log(friend.getGreeting()); // "hello, hi!"
console.log(relative.getGreeting()); // "hello, hi!"
 Copy code 

In depth series

1.JavaScript From prototype to prototype chain

2.JavaScript Deep lexical scope and dynamic scope

3.JavaScript Deep execution context stack

4.JavaScript Deep variable object

5.JavaScript Deep scope chain

6.JavaScript Follow in depth ECMAScript Normative interpretation this

7.JavaScript Deep execution context

8.JavaScript Deep closure

9.JavaScript In depth parameters are passed by value

10.JavaScript In depth call and apply Simulation Implementation of

11.JavaScript In depth bind Simulation Implementation of

12.JavaScript In depth new Simulation Implementation of

13.JavaScript Go deep into array objects and arguments

14.JavaScript Explore the various ways to create objects and their advantages and disadvantages

object-oriented

  • ES6 class grammar
  • Three elements
  • UML Class diagram
  • initialization npm Environmental Science
  • install webpack
  • install webpack-dev-server
  • install babel
  • npm init
  • package.json
// package.json
// "dev": "wepack --config ./webpack.dev.config.js --mode development"
{
"name": "design-pattern-text",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack-dev-server --config ./webpack.dev.config.js --mode development"
},
"author": "",
"license": "ISC",
"devDependencies": {
"html-webpack-plugin": "",
"webpack": "",
"webpack-cli": "",
"webpack-dev-server": ""
}
}
 Copy code 
  • npm install webpack webpack-cli --save-dev
  • webpack.dev.config.js
// webpack.dev.config.js
module.exports = {
entry: './src/index.js‘,
output: {
path: __dirname,
filename: './release/bundle.js'
}
}
 Copy code 
  • npm run dev
  • npm install webpack-dev-server html-webpack-plugin --save-dev
// webpack.dev.config.js
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry: './src/index.js‘,
output: {
path: __dirname,
filename: './release/bundle.js'
},
module: {
rules: [{
test: /\.js?$/,
exclude: /(node_modules)/,
loader: 'babel-loader' // es6 Grammar turns es5 grammar
}]
},
glugins: [
new HtmlWebpackPlugin({
template: './index.html'
})
],
devServer: {
contentBase: path.jon(__dirname,'./release'), // root directory
open: true, // Open browser automatically
port: 8080 // port
}
}
 Copy code 

analysis es6

  • npm install babel-core babel-loader babel-polyfill babel-preset-es2015 babel-preset-latest --save-dev
// root directory .babelrc
{
"presets": ["es2015", "latest"],
"plugins": []
}
 Copy code 

What is object-oriented

  1. Concept
  2. Three elements : Inherit , encapsulation , polymorphic
  3. JS Application examples of
  4. The meaning of object orientation

Example :

// class
class People {
constructor(name,age) {
this.name = name
this.age = age
}
eat() {
alert(`${this.name} eat something`)
}
speak() {
alert(`My name is ${this.name}, age ${this.age}`)
}
}
 Copy code 
// object ( example )
// Create examples
let da1 = new Perople('jeskson1', 12)
da1.eat()
da1.speak()
// Create examples
let da2 = new People('jeskson2', 13)
da2.eat()
da2.speak()
 Copy code 

Inherit , encapsulation , polymorphic

  1. Inherit , Subclass inherits parent
  2. encapsulation , Authority and confidentiality of data
  3. polymorphic , Different implementations of the same interface
// Inherit
class People {
constructor(name,age) {
this.name = name
this.age = age
}
eat() {
alert(`${this.name} eat something`)
}
speak() {
alert(`My name is ${this.name}, age ${this.age}`)
}
}
// Subclass inherits parent
class Student extends People {
constructor(name, age, number) {
super(name, age)
this.number = number
}
study() {
alert(`${this.name} study`)
}
}
 Copy code 
// example
let jeskson1 = new Student('da1', 10, '01')
jeskson1.study()
console.log(jeskson1.number)
jeskson1.eat()
 Copy code 

Inheritance can separate the common work method , Improve reuse

  • encapsulation (public Fully developed ,protected Open to subclasses ,private Open to yourself )
  • Use typescript
// encapsulation Parent class
class People {
public name
private age
protected weight
constructor(name, age) {
this.name = name
this.age = age
this.weight = 223
}
eat() {
alert(`${this.name} eat something`)
}
speak() {
alert(`My name is ${this.name}, age ${this.age}`)
}
}
 Copy code 
// Subclass
class Student extends People {
number
private grilfriend
constructor(name, age, number) {
super(name,age)
this.number = number
this.girlfriend = ' Little dance '
}
study() {}
getWeight() {}
}
 Copy code 

Reduce coupling , Not to expose ; Using data , Authority management of interface ; commonly _ The starting attribute is private

  • polymorphic : Different representations of the same interface
// Keep subclasses open and flexible
class People {
constructor(name) {
this.name = name
}
say() {}
}
class A extends People {
constructor(name) {
super(name)
}
say() {console.log('A dadaqianduan.cn')}
}
class B extends People {
constructor(name) {
super(name)
}
say() {console.log('B dadaqianduan.cn')}
}
let a = new A('a')
a.say()
let b = new b('b')
b.say()
 Copy code 
  • object-oriented : The order , Judge , loop , structured

UML Class diagram

image.png

image.png

15.JavaScript There are many ways and advantages and disadvantages of deep inheritance

JavaScript project

1.JavaScript The theme follows underscore Learn to resist shaking

In front-end development, we will encounter some frequent event triggers , Such as :

  1. window Of resize、scroll
  2. mousedown、mousemove
  3. keyup、keydown

2.JavaScript The theme follows underscore Learn to throttle

3.JavaScript The array of topics is de duplicated

4.JavaScript How to judge the type of topic ( On )

5.JavaScript How to judge the type of topic ( Next )

stay ES6 front ,JavaScript There are six data types

Undefined、Null、BooleanNumberStringObject
 Copy code 

image.png

[object Number]
[object String]
[object Boolean]
[object Undefined]
[object Null]
[object Object]
[object Array]
[object Date]
[object Error]
[object RegExp]
[object Function]
[object Math]
[object JSON]
[object Arguments]
 Copy code 
// jquery:
type: function(obj) {
if(obj == null) {
return obj + "";
}
return typeof obj === "object" || typeof obj === "function" ? class2type[toString.call(obj) ] || "object" : typeof obj;
}
 Copy code 

6.JavaScript A deep and shallow copy of the project

object : Objects are defined in two forms :1, The form of the statement ;2, Construction form

var myObj = {...};
var myObj = new Object();
 Copy code 

type : The object is JavaScript The basis of .6 Main types :

  1. string
  2. number
  3. boolean
  4. null
  5. undefined
  6. object

Simple basic type ,string, number, boolean, null, undefined It's not an object in itself ,null perform typeof null Will return a string object, actually ,null It's a basic type .

A function is a subtype of an object ,JavaScript The function in is “ First class citizen ”, Because they are essentially the same as ordinary objects , So you can manipulate functions just like you do other objects .

Common built-in objects :

  1. String
  2. Number
  3. Boolean
  4. Object
  5. Function
  6. Array
  7. Date
  8. RegExp
  9. Error

ES6 Defined Object.assign(...) Method to achieve shallow replication .

Object.assign(...) The first parameter of the method is the target object , After that, you can follow one or more source objects . It iterates over all enumerable private keys of one or more source objects and copies them to the target object , Finally, return the target object

Example :

function anotherFunction() { /*..*/ }
var anotherObject = {
c: true
};
var anotherArray = [];
var myObject = {
a: 2,
b: anotherObject, // quote , It's not a duplicate !
c: anotherArray, // Another reference !
d: anotherFunction
};
anotherArray.push( anotherObject, myObject );
var newObj = Object.assign( {}, myObject );
newObj.a; // 2
newObj.b === anotherObject; // true
newObj.c === anotherArray; // true
newObj.d === anotherFunction; // true
 Copy code 

property descriptor

var myObject = {
a: 2
};
Object.getOwnPropertyDescriptor(myObject, "a");
// {
// value: 2,
// writable: true,
// enumerable: true,
// configurable: true,
// }
// writable Can write
// enumerable enumerable
// configurable Configurable
 Copy code 
var myObject = {};
Object.defineProperty(myObject, "a", {
value: 2,
writable: true,
configurable: true,
enumerable: true
});
myObject.a; // 2
 Copy code 

Use defineProperty(...) to myObject Added a common property and explicitly specified some features .

  • writable Determine whether the value of the property can be modified

Example :

var myObject = {};
Object.defineProperty(myObject,"a",{
value: 2,
writable: false, // Don't write
configurable: true,
enumerable: true
});
myObject.a = 3;
myObject.a; // 2
 Copy code 
  • configurable, As long as the properties are configurable , You can use defineProperty(...) Method to modify the property descriptor .
var myObject = {
a: 2
};
myObject.a = 3;
myObject.a; // 3
Object.defineProperty(myObject, "a", {
value: 4,
writable: true,
configurable: false, // Not configurable
enumerable: true
});
myObject.a; // 4
myObject.a = 5;
myObject.a; //5
Object.defineProperty(myObject, "a", {
value: 6,
wirtable: true,
configurable: true,
enumerable: true
}); // TypeError
 Copy code 
  • enumerable, It controls whether properties appear in the object's property enumeration .
// Create a real constant property , Do not modify the , redefinition , Delete
var myObject = {};
Object.defineProperty(myObject, "a", {
value: 1,
writable: false,
configurable: false
});
 Copy code 
// No extension , Use Object.preventExtensions(...)
// Forbid stop One individual Yes like add Add new Belong to sex and And Protect leave has Yes Belong to sex
var myObject = {
a: 2
};
Object.preventExtensions(myObject);
myObject.b = 3;
myObject.b; // undefined
 Copy code 
  • seal up :Object.seal(...) Will create a “ seal up ” The object of , This method will actually call on an existing object Object.preventExtensions(...) And mark all existing attributes as configurable:false( While you can Modify the value of the property ).

  • frozen :Object.freeze(..) Will create a frozen object , This method will actually call on an existing object Object.seal(..) And put all “ The data access ” Property marked as writable:false, So you can't change their values .

getter,setter

  • getter It's a hidden function , Will be in Get attribute value Called when the
  • setter It's a hidden function , Will be in When setting property values call

Existence

Example :

var myObject = {
a: 2
};
("a" in myObject); // true
("b" in myObject); // false
myObject.hasOwnProperty("a"); // true
myObject.hasOwnProperty("b"); // false
 Copy code 
  • in The operator checks whether the property is in the object and [[Prototype]] In the prototype chain
  • hasOwnProperty(...) It only checks if the property is in myObject In the object , Will not check [[Prototype]] chain

enumeration

Example :

var myObject = {};
Object.defineProperty(
myObject,
"a",
{ enumerable: true, value: 2 }
);
Object.defineProperty(
myObject,
"b",
{ enumerable: false, value: 3}
);
myObject.b; // 3
("b" in myObject); // true
myObject.hasOwnProperty("b"); // true
for(var k in myObject) {
console.log(k, myObject[k]);
}
// "a" 2
 Copy code 

Check if the property is enumerable :

var myObject = {};
Object.defineProperty(
myObject,
"a",
{enumerable: true, value: 2}
);
Object.defineProperty(
myObject,
"b",
{enumerable: false, value:3}
);
myObject.propertyIsEnumerable("a"); // true
myObject.propertyIsEnumerable("b"); // false
Object.keys(myObject); // ["a"]
Object.getOwnPeropertyNames(myObject); // ["a", "b"]
 Copy code 
  • propertyIsEnumerable(...) Checks whether the given property name exists directly in the object , And satisfy enumerable: true

  • Object.keys(...) It returns an array , Contains all enumerable properties

  • Object.getOwnPropertyNames(...) It returns an array , Contains all properties , Whether they're enumerable or not

  • in and hasOwnProperty(...) The difference is whether to find [[Prototype]] chain

  • Object.keys(...) and Object.getOwnPropertyNames(...) Will only look up the properties directly contained in the object

have access to Object.preventExtensions(..)、Object.seal(..) and Object.freeze(..) To set the immutability level of an object .

Traverse

ES6 Method :forEach(),every(),some()

  • forEach(...) Will traverse all the values in the array and ignore the return value of the callback function
  • every(...) It runs until the callback function returns false
  • some(...) It runs until the callback function returns true

ES6 A new method for traversing arrays is added in for...of Cyclic grammar :

Example :

var myArray = [1,2,3];
for(var v of myArray) {
console.log(v);
}
// 1
// 2
// 3
 Copy code 

7.JavaScript The theme is realized from scratch jQuery Of extend

8.JavaScript How to find the maximum and minimum value of an array

image.png

var arr = [ 2,34,5,8];
function max(prev, next) {
return Math.max(prev, next);
}
console.log(arr.reduce(max));
 Copy code 
arr.sort(function(a,b){return a-b;});
console.log(arr[arr.length-1]);
 Copy code 
var max = eval("Math.max(" + arr + ")");
Math.max.applly(null, arr);
Math.max(...arr);
 Copy code 

9.JavaScript Flat array of topics

image.png

10.JavaScript Monographic study underscore Find the specified element in the array

11.JavaScript Special topic jQuery General traversal method each The implementation of the

12.JavaScript How to judge whether two objects are equal

Constructors , Class inheritance , Mix in

Constructors : Class instances are constructed by a special class method , This method name is usually the same as the class name , It's called a constructor . The task of this method is All the information needed to initialize the instance .

Class inheritance : In a class oriented language , You can define a class first , Then define a class that inherits the former . The latter is often called “ Subclass ”, The former is often called “ Parent class ”.

Mix in : When inheriting or instantiating ,JavaScript The object mechanism of does not automatically perform replication behavior . Simply speaking ,JavaScript There are only objects , There is no instantiation “ class ” The act of copying , stay JavaScript Simulates the replication behavior of classes in , This way is to mix in .

Two types of mixing :1, Explicit ;2, Implicit

Example :

function mixin( sourceObj, targetObj ) {
for (var key in sourceObj) {
// It will only be copied if it doesn't exist
if(!(key in targetObj)) {
targetObj[key] = sourceObj[key];
}
}
return targetObj;
}
var Vehicle = {
engines: 1,
ignition: function() {
console.log("truing on my engine");
},
drive: function() {
this.ignition();
console.log("steering and moving forward!");
}
};
var Car = mixin(Vehicle, {
wheels: 4,
drive: function() {
Vehicle.drive.call(this); // polymorphic
console.log(
"Rolling on all" + this.wheels + "wheels"
};
}
});
 Copy code 

Parasitic inheritance

A variant of the explicit blending pattern is called “ Parasitic inheritance ”, It's both explicit and implicit .

Example :

function Vehicle() {
this.engines = 1;
}
Vehicle.prototype.ignition = function() {
console.log("turning on my engine");
};
Vehicle.prototype.drive = function() {
this.ignition();
console.log("steering and moving forward");
};
// Parasitica Car
function Car() {
var car = new Vehicle();
car.wheels = 4;
var vehDrive = car.drive;
// rewrite
car.drive = function() {
vehDrive.call(this);
console.log("rolling on all" + this.wheels + "wheels");
return car;
}
myCar.drive();
 Copy code 

To blend in implicitly

Example :

var Something = {
cool: function() {
this.greeting = "hello world";
this.count = this.count ? this.count + 1 : 1;
}
};
Something.cool();
Something.greeting; / "hello world"
Something.count; // 1
var Another = {
cool: function() {
// Implicitly Something Mix in Another
Something.cool.call(this);
}
};
Another.cool();
Another.greeting; // "hello world"
Another.count; // 1 (count It's not a shared state )
 Copy code 

W3C Standard event flow

W3C Standard event flow : contain 3 Stages , Capture phase , Target stage , bubbling phase .

  1. In the capture phase , The event object propagates from the window to the parent of the target through the ancestor of the target .
  2. In the goal phase , The event object reaches the event target of the event object .
  3. In bubbling stage , Event objects propagate through the ancestors of the target in reverse order , Start with the parent of the target , By the end of the window .
  4. Start with the top-level objects window Start capturing all the way down , Until the target element , Then we go to the goal stage .
  5. Target element div After receiving the event, start bubbling to the top-level object window.
  6. Click <div> Elements , Event capture is first performed , At this point, press window→document→<html>→<body> Spread in the same order
  7. When the event object passes to <div> When we get to the goal stage , Then the event object passes from the target object to body, Thus the bubble stage of the event is entered
  8. Event objects press <body>→<html>→document→window The sequence of events .

image.png

13.JavaScript Currization of thematic functions

14.JavaScript Inert function of the topic

15.JavaScript Function combination of special topics

16.JavaScript Functional memory of special topics

17.JavaScript Recursion of the topic

18.JavaScript The disordered sequence of topics

19.JavaScript Interpretation of the topic v8 Sort source code

Prototype

JavaScript Objects in have a special [[Prototype]] Built in properties , It's actually a reference to other objects . Almost all objects are created [[Prototype]] Attributes are given a non empty value .

  • Use in Operator to check whether the attribute exists in the object , It also looks up the entire prototype chain of the object .

Example :

var anotherObject = {
a: 2
};
// Create an association to anotherObject The object of
var myObject = Object.create(anthorObject);
for(var k in myObject) {
console.log("found:" + k);
}
// found:a
("a" in myObject); // true
 Copy code 

Object.prototype

All ordinary [[Prototype]] The chain will eventually point to the built-in Object.prototype

By default, all functions have a function named prototype Public and enumerable properties of , It will point to another object

function Foo() {
// ...
}
Foo.prototype; // { }
 Copy code 

This object is often called Foo The prototype of the , Because we're going through a process called Foo.prototype To access it

var a = new Foo();
Object.getPrototypeOf( a ) === Foo.prototype; // true
 Copy code 

new Foo() A new object is generated , Internal links to this new object [[Prototype]] relation Yes. Foo.prototype object

Object.create(...) Will create a new object and associate it with the object we specify ,Object.create(null) Will create an object with an empty link , This object cannot delegate .

Because this object has no prototype chain , therefore instanceof The operator cannot judge , So it always comes back false. These special voids [[Prototype]] Objects are often called “ Dictionaries ”, They're not disturbed by the prototype chain at all , Great for storing data .

Example :

// polyfill Code
if(!Object.create) {
Object.create = function(o) {
function F(){}
F.prototype = o;
return new F(); // Construct a new object to associate
};
}
 Copy code 

Example :

var anotherObject = {
a: 2
};
var myObject = Object.create( anotherObject, {
b: {
enumerable: false,
writable: true,
configurable: false,
value: 3
},
c: {
enumerable: true,
writable: false,
configurable: false,
value: 4
}
});
myObject.hasOwnProperty( "a" ); // false
myObject.hasOwnProperty( "b" ); // true
myObject.hasOwnProperty( "c" ); // true
myObject.a; // 2
myObject.b; // 3
myObject.c; // 4
 Copy code 

image.png

Example :

var anotherObject = {
cool: function() {
console.log("cool");
}
};
var myObject = Object.create(anotherObject);
myObject.doCool = function() {
this.cool(); // Internal delegation
};
myObject.doCool(); // "cool"
 Copy code 

Use new When the function is called, the new object's .prototype Attribute is associated with “ Other objects ”. belt new The function call of is usually called “ Constructor call ”.

Objects are connected internally [[Prototype]] Chain related .

Example :

class Task {
id;
// Constructors Task()
Task(ID) { id = ID; }
outputTask() {output(id); }
}
class XYZ inherits Task {
label;
// Constructors XYZ()
XYZ(ID,Label) { super( ID ); label = Label; }
outputTask() { super(); output( label ); }
}
class ABC inherits Task {
// ...
}
 Copy code 

Recommended code :

Task = {
setID: function(ID) { this.id = ID; },
outputID: function() { console.log( this.id ); }
};
// Give Way XYZ entrust Task
XYZ = Object.create( Task );
XYZ.prepareTask = function(ID,Label) {
this.setID( ID );
this.label = Label;
};
XYZ.outputTaskDetails = function() {
this.outputID(); console.log( this.label );
};
// ABC = Object.create( Task );
 Copy code 

object-oriented :

function Foo(who) {
this.me = who;
}
Foo.prototype.identify = function() {
return "I am " + this.me;
};
function Bar(who) {
Foo.call( this, who );
}
Bar.prototype = Object.create( Foo.prototype );
Bar.prototype.speak = function() {
alert( "Hello, " + this.identify() + "." );
};
var b1 = new Bar( "b1" );
var b2 = new Bar( "b2" );
b1.speak();
b2.speak();
 Copy code 

Object association :

Foo = {
init: function(who) {
this.me = who;
},
identify: function() {
return "I am " + this.me;
}
};
Bar = Object.create( Foo );
Bar.speak = function() {
alert( "Hello, " + this.identify() + "." );
};
var b1 = Object.create( Bar );
b1.init( "b1" );
var b2 = Object.create( Bar );
b2.init( "b2" );
b1.speak();
b2.speak();
 Copy code 

Simpler design

Example :

// Parent class
function Controller() {
this.errors = [];
}
Controller.ptototype.showDialog(title,msg) {
// Show users titles and messages
};
Controller.prototype.success = function(msg) {
this.showDialog("Success", msg);
};
Controller.prototype.failure = function(err) {
this.errors.push(err);
this.showDialog("Error", err);
};
// Subclass
function LoginController() {
Controller.call(this);
}
// Associate a subclass with a parent
LoginController.prototype = Object.create(Controller.prototype);
LoginController.prototype.getUser = function() {
return document.getElementById("login_username").value;
};
LoginController.prototype.getPassword = function() {
return docuemnt.getElementById("login_password").value;
};
LoginController.prototype.validateEntry = function(user, pw) {
user = user || this.getUser();
pw = pw || this.getPassword();
if( !(user && pw) ) {
return this.failure(
"please enter a username & password!"
);
}
else if( user.length<5) {
return this.failuer(
"password must be 5+ characters"
);
}
// If it is executed here, it means it has passed the verification
return true;
};
// rewrite failure()
LoginController.prototype.failure = function(err) {
// "super" call
Controller.prototype.failure.call(
this,
"Login invalid" + err
);
};
// Subclass
function AuthController(login) {
Controller.call(this);
// synthesis
this.login = login;
}
// Associate a subclass with a parent
AuthController.prototype =
Object.crate(Controller.prototype);
AuthController.prototype.server = function(url, data) {
return $.ajax({
url: url,
data: data
});
};
AuthController.prototype.checkAuth = function() {
var user = this.login.getUser();
var pw = this.login.getPassword();
if (this.login.validateEntry(user.pw)) {
this.server( "/check-auth",{
user: user,
pw: pw
} ) .then( this.success.bind( this ) )
.fail( this.failure.bind( this ) );
}
};
// Rewrite the basic success()
AuthController.prototype.success = function() {
//“super” call
Controller.prototype.success.call( this, "Authenticated!" );
};
// Rewrite the basic failure()
AuthController.prototype.failure = function(err) {
//“super” call
Controller.prototype.failure.call(
this,
"Auth Failed: " + err
);
};
var auth = new AuthController();
auth.checkAuth(
// In addition to inheritance , We also need to synthesize
new LoginController()
);
 Copy code 

Object association :

var LoginController = {
errors: [],
getUser: function() {
return document.getElementById( "login_username" ).value;
},
getPassword: function() {
return document.getElementById( "login_password" ).value;
},
validateEntry: function(user,pw) {
user = user || this.getUser();
pw = pw || this.getPassword();
if (!(user && pw)) {
return this.failure( "Please enter a username & password!" );
}
else if (user.length < 5) {
return this.failure( "Password must be 5+ characters!" );
}
// If it is executed here, it means that it has passed the verification
return true;
},
showDialog: function(title,msg) {
// Show users titles and messages
},
failure: function(err) {
this.errors.push( err );
this.showDialog( "Error", "Login invalid: " + err );
}
};
// Give Way AuthController entrust LoginController
var AuthController = Object.create( LoginController );
AuthController.errors = [];
AuthController.checkAuth = function() {
var user = this.getUser();
var pw = this.getPassword();
if (this.validateEntry( user, pw )) {
this.server( "/check-auth",{
user: user,
pw: pw
} ) .then( this.accepted.bind( this ) )
.fail( this.rejected.bind( this ) );
}
};
AuthController.server = function(url,data) {
return $.ajax( {
url: url,
data: data
} );
};
AuthController.accepted = function() {
this.showDialog( "Success", "Authenticated!" )
};
AuthController.rejected = function(err) {
this.failure( "Auth Failed: " + err );
};
 Copy code 

Better grammar

Example :

class Foo { methodName() { /* .. */ } }
 Copy code 

image.png

Personal topics

Power button (LeetCode) subject

Nuggets article

️ Focus on + give the thumbs-up + Collection + Comment on + forward ️

give the thumbs-up 、 Collections and reviews

I am a Jeskson( Dada front end ), Thank you for your : give the thumbs-up 、 Collections and reviews , See you next time !( If there is something wrong with the content of this article , Welcome to point out * thank you , We learned together )

See you next time !

Articles are constantly updated , You can search through wechat 「 Dora, the programmer A dream 」 First time reading , reply 【 Information 】 I have the first-line factory information prepared by me , this paper www.1024bibi.com Included

github Included , welcome Stargithub.com/webVueBlog/…

版权声明
本文为[The devil Nezha]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/05/20210504182054674F.html

  1. Gallop workflow engine design series 01 process element design
  2. VUE移动端音乐APP学习【十六】:播放器歌词显示开发
  3. Vue Mobile Music App learning [16]: player lyrics display development
  4. jquery cookie
  5. jquery cookie
  6. 体面编码之JavaScript
  7. JavaScript for decent coding
  8. React17 系统精讲 结合TS打造旅游电商平台
  9. React17 system combined with TS to build tourism e-commerce platform
  10. 2021-05-04 hot news
  11. HttpSession对象与Cooike的关系 以及 Cookie对象构造函数问题
  12. gRPC-Web:替代REST的gRPC的Javascript库包
  13. The relationship between httpsession object and cooike and the construction of cookie object
  14. Grpc Web: a JavaScript library package to replace rest grpc
  15. Building reactive rest API with Java - kalpa Senanayake
  16. PDF转HTML工具——用springboot包装pdf2htmlEX命令行工具
  17. Pdf to HTML tool -- Wrapping pdf2htmlex command line tool with springboot
  18. PDF转HTML工具——用springboot包装pdf2htmlEX命令行工具
  19. Pdf to HTML tool -- Wrapping pdf2htmlex command line tool with springboot
  20. Vue.js比jQuery更容易学习
  21. Node.js的Reactor模式 与异步编程
  22. Vue. JS is easier to learn than jQuery
  23. Reactor mode of node.js and asynchronous programming
  24. 详解JavaScript中的正则表达式
  25. Explain regular expressions in JavaScript
  26. 详解JavaScript中的正则表达式
  27. Explain regular expressions in JavaScript
  28. JS: closure
  29. Write your own promise in promises / A + specification
  30. Analysis of the core mechanism of webpack from loader, plugin to egg
  31. On the import and export of webpack
  32. Interpretation of lodash source code (2)
  33. Hexo series (5) writing articles
  34. 有人用过JMeter或用HttpUnit写过测试吗????
  35. Has anyone ever used JMeter or written tests in httpUnit????
  36. JavaScript异步编程4——Promise错误处理
  37. Leetcode 1846. Reduce and rearrange the largest element of an array
  38. JavaScript asynchronous programming 4 -- promise error handling
  39. SQLite是一种经典的无服务器Serverless
  40. 通过Spring Boot Webflux实现Reactor Kafka
  41. SQLite is a classic server less
  42. Realization of reactor Kafka through spring boot Webflux
  43. Focus on the basic knowledge of JS
  44. Node.js与Spring Boot比较? - Ryan Gleason
  45. Compare node.js with spring boot- Ryan Gleason
  46. 「HTML+CSS」自定义加载动画【049】
  47. 「HTML+CSS」自定义加载动画【048】
  48. 「HTML+CSS」--自定义加载动画【047】
  49. "HTML + CSS" custom loading animation [049]
  50. "HTML + CSS" custom loading animation [048]
  51. "HTML + CSS" -- custom loading animation [047]
  52. 使用Akka实现Reactive DDD
  53. Prototype与JQuery对比
  54. Using akka to realize reactive DDD
  55. Comparison between prototype and jquery
  56. Please elaborate the diff algorithm of Vue
  57. On the combination of ecarts and Baidu map, in the Intranet environment to develop offline map, to achieve point, line, range value.
  58. 使用Slonik框架基于Node.js和PostgreSQL处理大量数据
  59. Using slonik framework to process large amount of data based on node.js and PostgreSQL
  60. Netflix使用React制作高性能电视用户界面