Propaganda: by the way: making source: stars ✨ | o | welcome star, encourage the author.
I hope I can help more friends. Add me 😚 can exchange problems (not big guy, learn from each other, create a good learning environment). Which of the following do you not understand?
- What do you not understand, we can comment below exchange
Extended object functionality
- Object classes
Call a function createPerson(), which creates an object:
function createPerson(name, age) {
return {
name: name,
age: age
};
}
Copy the 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 the code
When attributes in object literals have only names, the JS engine looks for variables with the same name in the surrounding scope. If found, the value of the variable will be assigned to the property of the same name as the object literal.
Es5 writing:
var person = { name: 'jeskson', sayName: function() { console.log(this.name); }};Copy the code
Es6 writing:
var person = { name: 'jeskson', sayName() { console.log(this.name); }};Copy the 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 the code
The two attribute names in the example contain Spaces and cannot be referenced using decimal notation, while the square bracket notation allows arbitrary strings to be used as attribute names.
Example optimization:
var person = {
"first name": "jeskson"
};
console.log(person["first name"]); // jeskson
Copy the code
var lastName = "last name";
var person = {
"first name": "da1",
[lastName]: "da2"
};
console.log(person["first name"]); // "da1"
console.log(person[lastName]); // "da2"
Copy the code
The square brackets inside the object literal indicate that the property name needs to be evaluated, resulting in 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 the code
- Equality operator
(= =)
Or strict equality operator(= = =)
- ES6:
Object.is()
, returns true, requiring that they are of the same type and have 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 the code
Object.assign()
methods
Mixins are the most popular pattern for combining objects in JS.
Shallow copy, when the property value is an object, only its reference is copied
function mixin(receiver, supplier) {
Object.keys(supplier).forEach(function(key) {
receiver[key] = supplier[key];
});
return receiver;
}
Copy the code
Object.assign() method, which takes a receiver and any number of providers and returns the receiver.
Example:
"use strict"; Var person = {name: "da1", name: "da2"}; console.log(person.name); // "da2"Copy the code
Enumeration order of its own properties
Modify the prototype of the object
Object.getPrototypeOf()
Method to get its prototype from any specified objectObject.setPrototypeOf()
Method to modify the stereotype 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); // trueCopy the code
Simple prototype access using super references
Object.getPrototypeOf()
Method ensures that the correct stereotype is called and appends a string to its return 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); // trueCopy the code
call(this)
To ensure that the prototype method is properly set up insidethis
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 the code
Using ES6 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 the code
In-depth series
1.JavaScript goes deep from prototype to prototype chain
- JavaScript goes from prototype to prototype chain
2.JavaScript deep lexical scope and dynamic scope
- JavaScript deep lexical scope and dynamic scope
3.JavaScript deep execution context stack
- JavaScript deep execution context stack
4.JavaScript deep variable objects
- JavaScript deep variable objects
5.JavaScript deep scope chain
- JavaScript deep scope chain
6.JavaScript reads this in depth from the ECMAScript specification
- JavaScript digs into this from the ECMAScript specification
7.JavaScript deep execution context
- JavaScript deep into the execution context
JavaScript deep closure
- JavaScript deep closure
9.JavaScript depth parameters are passed by value
- JavaScript depth parameters are passed by value
10.JavaScript deep simulation implementation of Call and apply
- JavaScript deep simulation of call and apply
11.JavaScript in-depth simulation of bind
- JavaScript in-depth simulation of bind implementation
12. Simulated implementation of JavaScript deep new
- JavaScript deep new simulation implementation
JavaScript delves into array objects and arguments
- JavaScript delves into things like array objects and arguments
14.JavaScript delves into the various ways of creating objects, as well as the pros and cons
- JavaScript delves into the many ways to create objects, as well as the pros and cons
object-oriented
- ES6 class grammar
- The three elements
UML
The class diagram- Initialize the
npm
The environment - The installation
webpack
- The installation
webpack-dev-server
- The installation
babel
npm init
package.json
// package.json // "dev": "wepack --config ./webpack.dev.config.js --mode development" { "name": "The design - the pattern - the 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 the 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 the 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 syntax to es5 syntax}]}, glugins: [ new HtmlWebpackPlugin({ template: './index.html' }) ], devServer: { contentBase: Path.jon (__dirname,'./release'), // root directory open: true, // automatically open browser port: 8080 // port}}Copy the code
Parsing es6
npm install babel-core babel-loader babel-polyfill babel-preset-es2015 babel-preset-latest --save-dev
/ / root directory. Babelrc {" presets ": [" es2015" and "latest"], "plugins" : []}Copy the code
What is object orientation
- concept
- Three elements: inheritance, encapsulation, polymorphism
- JS application examples
- Meaning of object orientation
Example:
Constructor (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 the code
Let da1 = new per1 ('jeskson1', 12) da1.eat() da1.speak() 13) da2.eat() da2.speak()Copy the code
Inheritance, encapsulation, polymorphism
- Inheriting. Subclasses inherit from their parent class
- Encapsulation, data permissions and confidentiality
- Polymorphic, different implementations of the same interface
Constructor (name,age) {this.name = name this.age = age} eat() {alert(' ${this.name} eat something`) } speak() { alert(`My name is ${this.name}, Class Student extends People {constructor(name, age, number) {constructor(name, age, number) {super(name, name); age) this.number = number } study() { alert(`${this.name} study`) } }Copy the code
// instance let jeskson1 = new Student('da1', 10, '01') jeskson1.study() console.log(jeskson1.number) jeskson1.eat()Copy the code
Inheritance can extract common-work method and improve reuse
- Encapsulation (
public
Fully developed,protected
Open to subclasses,private
Be open to yourself) - use
typescript
Class People {public name private age protected weight constructor(constructor) 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 the code
Class Student extends People {number private grilfriend constructor(name, age, constructor) Number) {super(name,age) this.number = number this.girlfriend = 'girlfriend'} study() {} getWeight() {}}Copy the code
Reduce coupling, do not expose what should not be exposed; Use data, interface authority management; Generally, attributes beginning with _ are private
- Polymorphism: Different manifestations of the same interface
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 the code
- Object oriented: order, judgment, loop, structuring
UML class diagrams
15. Multiple ways in which JavaScript extends inheritance and the pros and cons
- The various ways in which JavaScript extends inheritance and the pros and cons
JavaScript project
Underscore 1.JavaScript Topics follow underscore
- Underscore for JavaScript topics
Frequent event triggers are encountered in front-end development, such as:
Window resize, scroll
Mousedown, mousemove
Keyup, keydown
2.JavaScript topics follow the science of obscure
- JavaScript topics follow the science of underscore
3. Array de-duplication of JavaScript topics
- JavaScript topics for array de-duplication
4.JavaScript Topic Type Judgment (PART 1)
- Type Judgment of JavaScript Topics (PART 1)
5.JavaScript Topic Type Judgment (part 2)
- Type Judgment of JavaScript Topics (Part 2)
Before ES6, JavaScript had six data types
Undefined, Null,Boolean,Number,String,Object
Copy the code
[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 the 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 the code
6. Deep and shallow copy of JavaScript topics
-
Deep and shallow copy of JavaScript topics
-
Shallow copy: Copy reference methods, both of which change
-
Deep copy: Even if nested objects are separated from each other, they do not affect each other
Objects: Objects are defined in two forms: 1. 2. Structural form
var myObj = {... }; var myObj = new Object();Copy the code
Types: Objects are the foundation of JavaScript. There are 6 main types:
string
number
boolean
null
undefined
object
Simple basic types, string, number, Boolean, null, undefined itself is not an object, null returns the string object when typeof NULL is executed. In fact, NULL itself is a basic type.
A function is a subtype of an object, and functions in JavaScript are “first-class citizens” because they are essentially like normal objects and can be manipulated just like any other object.
Common built-in objects:
String
Number
Boolean
Object
Function
Array
Date
RegExp
Error
ES6 defines object.assign (…). Method to implement shallow copy.
Object.assign(…) The first argument to a method is the target object, which can be followed by one or more source objects. It iterates through all the enumerable keys of one or more source objects, copies them to the target object, and returns the target object
Example:
function anotherFunction() { /*.. */ } var anotherObject = { c: true }; var anotherArray = []; Var myObject = {a: 2, b: anotherObject, // 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; // trueCopy the code
Attribute descriptor
var myObject = { a: 2 }; Object.getOwnPropertyDescriptor(myObject, "a"); // { // value: 2, // writable: true, // enumerable: true, // configurable: //} // writable // enumerable // different configurableCopy the code
var myObject = {}; Object.defineProperty(myObject, "a", { value: 2, writable: true, configurable: true, enumerable: true }); myObject.a; / / 2Copy the code
Using defineProperty (…). Adds a common property to myObject and explicitly specifies some properties.
writable
Determines whether the value of an attribute can be modified
Example:
var myObject = {}; DefineProperty (myObject," A ",{value: 2, writable: false, // Writable: true, enumerable: true}); myObject.a = 3; myObject.a; / / 2Copy the code
configurable
Can be used as long as the property is configurabledefineProperty(...)
Method to modify the property descriptor.
var myObject = { a: 2 }; myObject.a = 3; myObject.a; // 3 Object.defineProperty(myObject, "A ", {value: 4, writable: true, different: false, // No configurable enumerable: true}); myObject.a; // 4 myObject.a = 5; myObject.a; //5 Object.defineProperty(myObject, "a", { value: 6, wirtable: true, configurable: true, enumerable: true }); // TypeErrorCopy the code
enumerable
, which controls whether a property appears in an object’s property enumeration.
Var myObject = {}; var myObject = {}; Object.defineProperty(myObject, "a", { value: 1, writable: false, configurable: false });Copy the code
// Disable extensions, use object.preventExtensions (...) Var myObject = {a: 2}; Object.preventExtensions(myObject); myObject.b = 3; myObject.b; // undefinedCopy the code
-
Seal: Object. Seal (…). Creates a “sealed” Object, this method actually calls Object.preventExtensions(…) on an existing Object. All existing attributes are tagged as 64x: False (although the values of the attributes can be modified).
-
Freeze: Object. Freeze (..) Creates a frozen Object. This method actually calls Object.seal(..) on an existing Object. And mark all “data access” properties as writable:false so that their values cannot be changed.
getter
,setter
getter
Is a hidden function that will be inGet property valuesCalled when thesetter
Is a hidden function that will be inWhen setting the property valuecall
existence
Example:
var myObject = {
a: 2
};
("a" in myObject); // true
("b" in myObject); // false
myObject.hasOwnProperty("a"); // true
myObject.hasOwnProperty("b"); // false
Copy the code
in
The operator checks whether the property is in the object and[[Prototype]]
In the prototype chainhasOwnProperty(...)
It only checks if the property is inmyObject
Object is not checked[[Prototype]]
chain
The 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 the code
Check if properties are 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 the code
-
propertyIsEnumerable(…) Enumerable: True Checks if the given attribute name exists directly in the object
-
Object.keys(…) Returns an array containing all the enumerable properties
-
Object.getOwnPropertyNames(…) Returns an array containing all properties, whether they are enumerable or not
-
In and hasOwnProperty (…). The difference is whether to look for the [[Prototype]] chain
-
Object.keys(…) And the Object. GetOwnPropertyNames (…). Will only look for properties directly contained in the object
Use object.preventExtensions (..) And the Object. Seal (..) And the Object. Freeze (..) To set the immutability level of the object.
traverse
ES6 method: forEach(),every(),some()
forEach(...)
All values in the array are iterated and the return value of the callback function is ignoredevery(...)
Will run until the callback returns falsesome(...)
Will run until the callback returns true
ES6 has a new for… Of loop syntax:
Example:
Var myArray on = [1, 2, 3]; for(var v of myArray) { console.log(v); } // 1/2/3Copy the code
7.JavaScript topics from zero implementation of jQuery extend
- JavaScript topics from zero implementation of jQuery extend
8. How to maximize and minimize arrays
- How to maximize and minimize arrays
Var arr = [2,34,5,8]; function max(prev, next) { return Math.max(prev, next); } console.log(arr.reduce(max));Copy the code
arr.sort(function(a,b){return a-b; }); console.log(arr[arr.length-1]);Copy the code
var max = eval("Math.max(" + arr + ")"); Math.max.applly(null, arr); Math.max(... arr);Copy the code
9. Array flattening for JavaScript topics
- JavaScript topic array flattening
10. Underscore looks for a specified element in an array
- Science of JavaScript Topics underscore looks up a specified element in an array
11. Implementation of jQuery common traversal method each for JavaScript topic
- The implementation of jQuery common traversal method each
12.JavaScript topic how to determine the equality of two objects
- How to determine the equality of two objects
Constructor, class inheritance, mixed in
Constructor: A class instance is constructed from a special class method, usually with the same name as the class, called a constructor. The task of this method is to initialize all the information needed for the instance.
Class inheritance: In a class-oriented language, you can define a class and then define a class that inherits from the former. The latter is often referred to as a “subclass” and the former as a “parent class.”
Mixin: JavaScript’s object mechanism does not automatically perform copying behavior when inherited or instantiated. Simply put, there are only objects in JavaScript, and there is no “class” copy behavior that can be instantiated. To simulate the class copy behavior in JavaScript, this method is called blending.
Two types of mixing: 1, explicit; 2, implicit
Example:
Function mixin(sourceObj, targetObj) {for (var key in sourceObj) {// Only copy 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); // multistate console.log("Rolling on all" + this.wheels + "wheels"}; }});Copy the code
Parasitic inheritance
A variant of the explicit mixin pattern is known as “parasitic inheritance”, which is 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"); }; Function Car() {var Car = new Vehicle(); car.wheels = 4; var vehDrive = car.drive; Drive = function() {vehdrive.call (this); console.log("rolling on all" + this.wheels + "wheels"); return car; } myCar.drive();Copy the code
Implicit in
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() {cool.call(this); }}; Another.cool(); Another. The greeting; // "hello world" Another.count; // 1 (count is not shared)Copy the code
W3C standard event flow
W3C standard event flow: contains 3 phases: capture phase, target phase, and bubble phase.
- In the capture phase, the event object is propagated from the window to the target’s parent through the target’s ancestor.
- In the target phase, the event object reaches the event target of the event object.
- In the bubbling phase, event objects propagate through the target’s ancestors in reverse order, starting with the target’s parent and ending with the window.
- Let’s start with the top-level object
window
Start trapping all the way down until the target element is reached, and then enter the target phase. - The target element div receives the event and starts bubbling up to the top-level object
window
. - Click on the
<div>
Element, event capture is first performed, at which point the event pressWindow to the document - > < HTML >, < body >
In order to propagate - When the event object passes
<div>
Then the event object is passed from the target objectbody
To enter the bubbling phase of the event - Event object press
The < body > > < HTML > > document to the window
To propagate events in sequence.
13. Currification of JavaScript thematic functions
- Currization of JavaScript topics
14.JavaScript thematic lazy functions
- Lazy functions for JavaScript topics
15.JavaScript thematic function composition
- JavaScript thematic function composition
16. Functional memory for JavaScript topics
- Functional memory for JavaScript topics
17. Recursion of JavaScript topics
- Recursion of JavaScript topics
18.JavaScript topics out of order
- JavaScript topics out of order
19.JavaScript thematic interpretation of V8 sort source code
- JavaScript thematic interpretation of v8 sort source code
The prototype
Objects in JavaScript have a special [[Prototype]] built-in property that is essentially a reference to another object. Almost all objects are created with a non-null value for the [[Prototype]] property.
- use
in
Operator to check whether a property exists in an object, also looks for the entire prototype chain of the object.
Example:
var anotherObject = { a: 2 }; Var myObject = object.create (anthorObject); // Create an Object associated with anotherObject. for(var k in myObject) { console.log("found:" + k); } // found:a ("a" in myObject); // trueCopy the code
Object.prototype
All normal [[Prototype]] chains end up pointing to the built-in Object.prototype
By default, all functions have a public, non-enumerable property called Prototype that points to another object
function Foo() {
// ...
}
Foo.prototype; // { }
Copy the code
This object is often referred to as a prototype of Foo because we access it through a property reference named foo.prototype
var a = new Foo();
Object.getPrototypeOf( a ) === Foo.prototype; // true
Copy the code
New Foo() generates a new object whose internal link [[Prototype]] is associated with the foo.prototype object
Object.create(…) Object.create(null) creates an Object with an empty link that cannot be delegated.
Because this object has no prototype chain, the instanceof operator cannot determine this and will always return false. These special empty [[Prototype]] objects, often referred to as “dictionaries,” are completely undisturbed by the Prototype chain and are perfect for storing data.
Example:
// Polyfill if(! Object.create) { Object.create = function(o) { function F(){} F.prototype = o; return new F(); // create a new object to associate with}; }Copy the 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; / / 4Copy the code
Example:
var anotherObject = { cool: function() { console.log("cool"); }}; var myObject = Object.create(anotherObject); myObject.doCool = function() { this.cool(); // internal delegate}; myObject.doCool(); // "cool"Copy the code
Calling a function with new associates the.prototype property of the new object with “other objects”. A function call with new is often called a “constructor call.”
Objects are related via an internal [[Prototype]] chain.
Example:
class Task { id; // constructor Task() Task(ID) {ID = ID; } outputTask() {output(id); } } class XYZ inherits Task { label; Constructor XYZ() XYZ(ID,Label) {super(ID); label = Label; } outputTask() { super(); output( label ); } } class ABC inherits Task { // ... }Copy the code
Recommended code:
Task = { setID: function(ID) { this.id = ID; }, outputID: function() { console.log( this.id ); }}; // assign 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 the 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 the 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 the code
Simpler design
Example:
Function Controller() {this.errors = []; } Controller. Ptototype. ShowDialog (title, MSG) {/ / titles to the user and message}; 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); } / / the subclasses associated to the parent class LoginController. Prototype = Object. The create (Controller. The 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" ); } return true; }; / / rewrite failure () LoginController. Prototype. Failure = function (err) {/ / called "super" Controller. The prototype. Failure. The call ( this, "Login invalid" + err ); }; // Subclass function AuthController(login) {controller.call (this); // synthesize this.login = login; 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 foundation of success () AuthController. Prototype. Success = function () {/ / called "super" Controller. The prototype. Success. The call (this, "Authenticated!" ); }; / / rewrite based failure () AuthController. Prototype. Failure = function (err) {/ / called "super" Controller. The prototype. Failure. The call ( this, "Auth Failed: " + err ); }; var auth = new AuthController(); Auth.checkauth (// In addition to inheritance, we also need to synthesize new LoginController());Copy the 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!" ); } return true; }, showDialog: function(title, MSG) {failure: function(err) {this.errors.push(err); this.showDialog( "Error", "Login invalid: " + err ); }}; 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 the code
Better syntax
Example:
class Foo { methodName() { /* .. * /}}Copy the code
Individual projects
📚 force buckle (LeetCode) topic
- Sum of two numbers, valid parentheses, sum of two numbers
- Merges two ordered lists, removes duplicates in sorted arrays,JavaScript notes
- LeetCode – Maximum suborder sum,JavaScript Data Structures and Algorithms (Arrays)
- Force buckle (LeetCode)- stack, parenthesis generation | brush title punch card
- Force buckle (LeetCode)- plus one, queue | swipe question punch
- Force button (LeetCode)- Merge two ordered arrays, dictionary, hash table | swipe card
- Force buckle (LeetCode)- Symmetric binary tree, tree | brush title punch card
- Force buckle (LeetCode)-104. Maximum depth of binary tree, figure | brush problem punch
- Sorting, searching, the algorithm model, the algorithm complexity | comprehensive notes data structures and algorithms
- LeetCode -28. Implement strStr()
- LeetCode -14. The longest public prefix
- LeetCode -13. Convert Roman numerals to integers
📚 Nuggets article
- Daily Front-end summary
- A rare primer on TypeScript systems
- JS Sunflower treasure Book secret notes, escort for you gold three silver four
- TypeScript learns early to become competitive in the workplace
- More than 234.77 million words in front-end simulation interview
- JavaScript data structure of the chain table | technical review
- JavaScript data structures – Collections | Technical Review
- This was my first JavaScript primer
- A qualified junior front-end engineer needs to master module notes
- [Primary] Personally share notes of Vue front-end development tutorial
- LocalStorage and sessionStorage localStorage
- Drag and drop in HTML5
- Challenge the front-end HTTP/ECMAScript
- 170 Interview questions + answer Learn to organize (conscience making)
- Must learn must learn – Audio and video
- Front-end HTML5 interviewers and candidates ask and answer questions
- Vue.js pen test questions Solve common business problems
- ES6 comprehensive summary
- MySQL database (RDBMS)
- A long summary of JavaScript to consolidate the front end foundation
- Learn the summary of HTML5 finger front-end (suggested collection, illustrated)
- Front-end must learn must know – multimedia – local storage – browser and server interaction – communication function
- [Suggestion 👍] Record an interview for front-end JavaScript of a BAT first-line Internet company
- Web page creation basics
- 【 Mind Mapping 】 Front-end development – consolidate your JavaScript knowledge
- [Illustrated, like collection oh!] Re-study to reinforce your Vuejs knowledge
- How to obtain a high note 】 【 thrilling front-end offer essay | the nuggets technology
- Mandatory guide for phase 11 Front-end Sprints – Execution context/scope chain/closure/First class citizen
- 12) front sprint must-have guide – HTTP/HTTPS/HTTP2 / DNS/TCP/classic problem
- This /call/apply/bind
- 14 – even liver 7 nights, summed up the computer network knowledge point! (66 items in total)
- HTML5 Canvas (10 points in total)
- Issue 16 – staying up for 7 days, I summarized 25 important things about JavaScript and ES!
- Issue 17 – What is a MySQL database? This one dry article is enough!
- Issue 18 – Back end Attack, a rare PHP learning guide
- Issue 19 – When you search for keywords on Baidu, which website comes first? Today give you a popular science “website SEO”
- Front end learning, experience sharing, sharing process of project technical essay | the nuggets – double festival special articles
- To the front-end programmers English study guide | nuggets technical essay – double festival special articles
- [Illustrated, like collection oh!] Relearn to reinforce your Vuejs Knowledge (PART 1)
- [Illustrated, like collection oh!] Relearn to reinforce your Vuejs knowledge (part 2)
- 【 Mind Mapping 】 Front-end development of JavaScript- consolidate your JavaScript knowledge
- (a) proficient in HTML5+CSS3, review once a day
- The interviewer started by asking me about Chrome’s underlying principles and HTTP protocol (swastika)
- 2020 “I and technical interview those things” | Denver annual essay
- “Advanced” the interviewer asked me Chrome rendering principle | Denver annual essay (6000 words long)
- 2020 small application development – cloud development technical summary | Denver annual essay
- Tencent location service application development | creator training camp
- Dada front-end personal web sharing additional answer | 92 JavaScript interview problem creator training camp
- This year received books, thanks for the gift! Review 2020, outlook 2021 | Denver annual essay
- Flex layout – Seven days of punching
- Say something about CSS | Technical Comments
- It wasn’t that hard! Vue mall development | technical review
❤️ follow + like + Favorite + comment + forward ❤️
Likes, favorites and comments
I’m Jeskson, thanks for your talent: likes, favorites and comments, and we’ll see you next time! ☞ Thank you for learning with me.
See you next time!
This article is constantly updated. You can search “Programmer Doraemon” on wechat to read it for the first time, and reply [information] there are materials of first-line big factories prepared by me, which have been included in this article www.1024bibi.com
Star: github.com/webVueBlog/…
- Hand in your homework technology creators, come here quickly! | creator camp phase ii