Skill notes that a qualified intermediate front-end engineer needs to master (on)

Skill notes that a qualified intermediate front-end engineer needs to master (on)

Github source: Skills that a qualified intermediate front-end engineer needs to master | Seeking stars | Give me Follow, Like, Encourage the author

Hello everyone, I m the Devil Nezha , I m glad to meet you~~

Nezha's life creed: If you like what you are learning, you will have a strong motivation to support it .

Learning programming every day will make you a step away from your dreams. Thank you to every programmer who loves programming. No matter how wonderful the knowledge is, join me and let the wandering heart settle down, keep going, come on,

2021
Come on! Welcome to follow and add me
vx:xiaoda0423
, Likes, favorites and comments are welcome

Don't be afraid of dreaming, but don't just dream. Be a doer, not a talker, and seek truth and practice.

Preface

If this article is helpful to you, give follow, like, encourage the author, have you accepted the challenge? Article number starting public concern programmer A Dream first time to get the latest articles

Refill ~

Have read:

  1. ES6 series of let and const
  2. ES6 series template string
  3. Arrow function of ES6 series
  4. The simulation of the ES6 series implements the Symbol type
  5. ES6 series of iterators and for of
  6. The simulation of the ES6 series implements a Set data structure
  7. WeakMap of ES6 series
  8. Let's talk about Promise of ES6 series
  9. ES6 complete user manual
  10. DefineProperty and proxy of ES6 series
  11. Module loading scheme of ES6 series
  12. Implementation of ES6 series of private variables
  13. Front end, school recruitment, face Taobao, guide
  14. Front end, social recruitment, face Taobao, guide
  15. You are working hard to do business, and your performance is not very good. I can only help you here...
  16. The live Q&A text record of the head of the front-end school recruitment of the Tao Department
  17. A letter to the 2021 front-end classmates | Forge ahead, the future can be expected!
  18. Don t panic when asked about the project experience in the interview, the answer according to this step is absolutely amazing
  19. The project does not know how to optimize performance? Might as well try code splitting

HTML module

HTML tags contain some special "elements" such as:

<head> <title> <body> <header> <footer> <article> <section> <p> <div> <span> <img> <aside> <audio> <canvas> <datalist> <details> <embed> <nav> <output> <progress> <video>

article

Represents an independent structure in a document, page, application, or website. It is intended to be an independently assignable or reusable structure. For example, it may be a forum post, a magazine or news article, a blog, or a user-submitted comment during publishing. , Interactive components, or other independent content items.

section element

Represents an independent part contained in an HTML document. It has no more specific semantic elements to represent it. Generally speaking, it contains a title.

aside element

Indicates a part that is almost irrelevant to the content of the rest of the page. It is considered to be a part independent of the content and can be split separately without affecting the whole.

audio element

Used to embed audio content in the document.

<audio controls src="/zzz.mp3"> dada <code>audio</code>. </audio> Copy code

canvas element

Used to draw graphics and graphics animations through JavaScript (Canvas API or WebGL API).

<canvas id="canvas" width="300" height="300"></canvas> var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); ctx.fillStyle ='green'; ctx.fillRect(10, 10, 100, 100); Copy code

datalist element

Contains a set of

<option>
Elements, these elements represent optional values for other form controls.

<input list="browsers" name="myBrowser"/></label> <datalist id="browsers"> <option value="Chrome"> <option value="Firefox"> <option value="Internet Explorer"> <option value="Opera"> <option value="Safari"> </datalist> Copy code

details element

A pendant can be created, and only when it is switched to the expanded state, it will display the information contained in it.

<summary>
Elements can provide a summary or label for the part.

<details> <summary>System Requirements</summary> <p>Requires a computer running an operating system. The computer must have some memory and ideally some kind of long-term storage. An input device as well as some form of output device is recommended.</p> </details> Copy code
System Requirements

Requires a computer running an operating system. The computer must have some memory and ideally some kind of long-term storage. An input device as well as some form of output device is recommended.

embed element

External content embedded elements

progress element

Used to display the progress of a task

<progress id="file" max="100" value="70"> 70% </progress> Copy code

output tags

Indicates the result of calculation or user operation.

nav element

Represents a part of a page whose purpose is to provide navigation links in the current document or other documents

Form widget:

<form action="/my-handling-form-page" method="post"> <div> <label for="name">Name:</label> <input type="text" id="name"> </div> <div> <label for="mail">E-mail:</label> <input type="email" id="mail"> </div> <div> <label for="msg">Message:</label> <textarea id="msg"></textarea> </div> </form>

<input type="text" id="comment" name="comment" value="I'm a text field">

E-mail

<input type="email" id="email" name="email" multiple>

<input type="password" id="pwd" name="pwd">

<input type="search" id="search" name="search">

<input type="tel" id="tel" name="tel">

URL :

<input type="url" id="url" name="url">

:

<textarea cols="30" rows="10"></textarea>

:

<input type="checkbox" checked id="carrots" name="carrots" value="carrots">

:

<input type="radio" checked id="soup" name="meal">

:

<input type="number" name="age" id="age" min="1" max="10" step="2">

:

<input type="range" name="beans" id="beans" min="0" max="500" step="10">

:

<input type="datetime-local" name="datetime" id="datetime"> <input type="month" name="month" id="month"> <input type="time" name="time" id="time"> <input type="week" name="week" id="week">

:

<input type="color" name="color" id="color">

:

<input type="file" name="file" id="file" accept="image/*" multiple>

:

<input type="hidden" id="timestamp" name="timestamp" value="6354561">

/

( web ) ( Apache Nginx IIS Tomcat web ) HTTP

: :

action attribute-this attribute defines where to send the data.

method attribute-this attribute defines how to send data.

What is form data validation?

Visit any website with a registration form, and you will find that when you submit a form without entering information in the expected format, the registration page will give you a feedback.

  • "This field is required" (this field cannot be left blank)
  • Please enter your phone number
  • Please enter a valid email address

Use regular expression verification

Example:

a matches a character a (cannot match b, aa, etc.) abc matches a, followed by b, and finally c. a* match 0 or more characters a (+ means match at least one or more). [^a] matches a character, but it cannot be a. a|b matches a character a or b. [abc] Match a character, it can be a, b or c. [^abc] matches a character, but it cannot be a, b or c. [az] Match the character range az and all lowercase (you can use [A-Za-z] to cover case, or [AZ] to restrict uppercase). ac-matches the character a, matches any character in the middle, and finally matches the character c. a{5} Match the character a five times. a{5,7} Match the character a five to seven times, no more or less. Copy code

AJAX technology mainly relies on XMLHttpRequest (XHR) DOM objects. It can construct HTTP requests, send them, and get the result of the request.

Form data (

application/x-www-form-urlencoded
) Consists of a list of URL-encoded key/value pairs. In order to transmit binary data, HTTP requests are reintegrated into
multipart/form-data
form.

Construct

XMLHttpRequest
:
XMLHttpRequest
It is the safest and most reliable way to make HTTP requests.

Example:

function sendData(data) { var XHR = new XMLHttpRequest(); var urlEncodedData = ""; var urlEncodedDataPairs = []; var name; //Convert the data object into an array of URL-encoded key/value pairs. for(name in data) { urlEncodedDataPairs.push(encodeURIComponent(name) +'=' + encodeURIComponent(data[name])); } //Combine the pairs into a single string and replace all %-encoded spaces with //"+" character; matches the behavior of browser form submission. urlEncodedData = urlEncodedDataPairs.join('&').replace(/%20/g,'+'); //Define what happens when the data is submitted successfully XHR.addEventListener('load', function(event) { alrt('Yeah! The data has been sent and the response has been loaded.'); }); //Define the error message XHR.addEventListener('error', function(event) { alrt(' '); }); // XHR.open('POST', 'https://example.com/cors.php'); // POST HTTP XHR.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); // XHR.send(urlEncodedData); }

FormData

function sendData(data) { var XHR = new XMLHttpRequest(); var FD = new FormData(); // FormData for(name in data) { FD.append(name, data[name]); } // XHR.addEventListener('load', function(event) { alrt('Yeah! '); }); // XHR.addEventListener('error', function(event) { alrt('Oops! '); }); // XHR.open('POST', 'https://example.com/cors.php'); // formData ,HTTP XHR.send(FD); }

FormData

<form id="myForm"> <label for="myName"> </label> <input id="myName" name="name" value="John"> <input type="submit" value=" "> </form>

window.addEventListener("load", function () { function sendData() { var XHR = new XMLHttpRequest(); //We bind this FormData and form elements together. var FD = new FormData(form); //We define what happens when the data is successfully sent. XHR.addEventListener("load", function(event) { alrt(event.target.responseText); }); //We define what will happen in case of failure XHR.addEventListener("error", function(event) { alrt('Oh! Something went wrong.'); }); //we set up our request XHR.open("POST", "https://example.com/cors.php"); //The data sent is provided by the user in the form XHR.send(FD); } //we need to get form elements var form = document.getElementById("myForm"); //...then take over the submission event of the form form.addEventListener("submit", function (event) { event.preventDefault(); sendData(); }); }); Copy code

CORS
Handling cross-domain images

By collocation

crossorigin
Attributes and appropriate
CORS
Header, in
<img>
The image defined in the element can be loaded from an external source and placed in
<canvas>
Used in the element as if it were loaded from a local source.

Enabled

CORS
picture of

Even if you don t pass CORS, you can

<canvas>
Use pictures from other sources, but this will contaminate the canvas and is no longer considered a safe canvas.
<canvas>
An exception was thrown during data retrieval.

Call the following methods in the "contaminated" canvas:

  • in
    <canvas>
    Call on the context of
    getImageData()
    • in
      <canvas>
      Call up
      toBlob()
  • in
    <canvas>
    Call up
    toDataURL()

CORS
Set properties

Some provide

CORS
Supported
HTML
Elements such as
<img>
or
<video>
,have
crossorigin
Element attributes/
attribute
(
crossOrigin
Object attributes/
property
), this attribute enables you to configure its cross-domain resource acquisition request.

CanvasRenderingContext2D.getImageData()

CanvasRenderingContext2D.getImageData()
Return a
ImageData
Object, used to describe
canvas
The pixel data implied by the area, this area is represented by a rectangle,
The starting point is (sx, sy), the width is sw, and the height is sh
.

syntax

ImageData ctx.getImageData(sx, sy, sw, sh); sx The x coordinate of the upper left corner of the rectangular area of the image data to be extracted. sy The y coordinate of the upper left corner of the rectangular area of the image data to be extracted. sw The width of the rectangular area of the image data to be extracted. sh The height of the rectangular area of the image data to be extracted. return value An ImageData object that contains the rectangular image data given by the canvas. Copy code

Use the getImageData method:

<canvas id="canvas"></canvas> var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); ctx.rect(10, 10, 100, 100); ctx.fill(); console.log(ctx.getImageData(50, 50, 100, 100)); //ImageData {width: 100, height: 100, data: Uint8ClampedArray[40000]} return value An ImageData object that contains the rectangular image data given by the canvas. Copy code

HTMLCanvasElement.toBlob()

HTMLCanvasElement.toBlob()
Method creation
Blob
Object to show
canvas
The picture above; this picture file can be cached or saved locally, at the discretion of the user agent. Unless otherwise specified, the type of picture defaults to
image/png
With a resolution of
96dpi
.

syntax

canvas.toBlob(callback, type, encoderOptions); callback The callback function can obtain a single Blob object parameter. type optional DOMString type, specify the image format, the default format is image/png. encoderOptions optional Number type, the value is between 0 and 1, used to specify the image display quality when the requested image format is image/jpeg or image/webp. If the value of this parameter is not within the specified type and range, the default value will be used, and the remaining parameters will be ignored. return value no. Copy code

HTMLCanvasElement.toDataURL()

HTMLCanvasElement.toDataURL()
Method returns an image display
data URI
. can use
type
The type of the parameter, the default is
PNG
format. The resolution of the picture is
96dpi
.

  • If the height or width of the canvas is 0, then the string "
    data:,
    ".
  • If the type passed in is not "
    image/png
    ", but the returned value is
    "Data:image/png"
    At the beginning, then the incoming type is not supported.
  • Chrome supports "
    image/webp
    "Types of.

syntax

canvas.toDataURL(type, encoderOptions); type optional Picture format, the default is image/png encoderOptions optional When the specified image format is image/jpeg or image/webp, the quality of the image can be selected from 0 to 1. If it exceeds the value range, the default value of 0.92 will be used. Other parameters will be ignored. return value The DOMString containing the data URI. Copy code

Example:

<canvas id="canvas" width="5" height="5"></canvas> var canvas = document.getElementById("canvas"); var dataURL = canvas.toDataURL(); console.log(dataURL); //"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNby //blAAAADElEQVQImWNgoBMAAABpAAFEI8ARAAAAAElFTkSuQmCC" Copy code

Set the quality of the picture:

var fullQuality = canvas.toDataURL("image/jpeg", 1.0); //data:image/jpeg;base64,/9j/4AAQSkZJRgABAQ...9oADAMBAAIRAxEAPwD/AD/6AP/Z" var mediumQuality = canvas.toDataURL("image/jpeg", 0.5); var lowQuality = canvas.toDataURL("image/jpeg", 0.1); Copy code

Allow browsers to allow cross-domain access requests when downloading image data

The download starts when the user clicks the "Download" button:

function startDownload() { let imageURL = "https://xxxx"; downloadedImg = new Image; downloadedImg.crossOrigin = "Anonymous"; downloadedImg.addEventListener("load", imageReceived, false); downloadedImg.src = imageURL; } Copy code

canvas
of
toDataURL()
Method is used to convert the image to
data://URL
Form
PNG
Format picture

by

rel="preload"
Content preload

<link>
The most common use case for tags is to be used to load
CSS
File to decorate your page:

<link rel="stylesheet" href="styles/main.css"> <link rel="preload" href="style.css" as="style"> <link rel="preload" href="main.js" as="script"> Copy code

What types of content can be preloaded?

audio: audio file. document: An HTML document to be embedded in <frame> or <iframe>. embed: A resource that will be embedded inside the <embed> element. fetch: Those resources that will be obtained through fetch and XHR requests, such as an ArrayBuffer or JSON file. font: Font file. image: Picture file. object: A file that will be embedded in the <embed> element. script: JavaScript file. style: style sheet. track: WebVTT file. worker: A JavaScript web worker or shared worker. video: Video file. Copy code

How to make a fast loading HTML page

  1. Reduce the size of the page.
  2. Minimize the number of files: Reducing the number of files referenced by a page can reduce the number of HTTP requests required in the process of downloading a page, thereby reducing the time for sending and receiving these requests.
  3. Use CDN.
  4. Reduce domain name lookup: Each independent domain name consumes DNS lookup time, and the page load time will increase with the number of independent domain names, CSS links, JavaScript and image resources.
  5. :

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Vector versus raster</title> </head> <body> <h1>Vector versus raster</h1> <img src="star.png" alt="A raster star"> <img src="star.svg" alt="A vector star"> </body> </html>

<svg version="1.1" baseProfile="full" width="300" height="200" xmlns="http://www.w3.org/2000/svg"> <rect width="100%" height="100%" fill="black"/> <circle cx="150" cy="100" r="90" fill="blue"/> </svg>

<img src="equilateral.svg" alt="triangle with all three sides equal" height="87px" width="100px"/> Copy code
<svg width="300" height="200"> <rect width="100%" height="100%" fill="green"/> </svg> Copy code

Use SVG:

<svg width="100%" height="100%"> <rect width="100%" height="100%" fill="red"/> <circle cx="100%" cy="100%" r="150" fill="blue" stroke="black"/> <polygon points="120,0 240,225 0,225" fill="green"/> <text x="50" y="100" font-family="Verdana" font-size="55" fill="white" stroke="black" stroke-width="2"> Hello! </text> </svg> Copy code

CSS module

Overlapping margins

Top margin of block

(margin-top)
And bottom margin
(margin-bottom)
Sometimes merging (folding) into a single margin, whose size is the maximum value of a single margin (or if they are equal, only one of them), this behavior is called margin folding.

Layout and containing blocks

Cascading context

Elements that meet any of the following conditions are formed:

  • Document root element (
    <html>
    );
  • position
    Value is
    absolute
    (Absolute positioning) or
    relative
    (Relative positioning) and
    z-index
    Value is not
    auto
    Elements;
  • position
    Value is
    fixed
    (Fixed positioning) or
    sticky
    (Sticky positioning) element (sticky positioning adapts to browsers on all mobile devices, but old desktop browsers do not support it);
  • flex (
    flexbox
    ) A child element of the container, and
    z-index
    The value is not auto;
  • grid (
    grid
    ) A child element of the container, and
    z-index
    The value is not auto;
  • opacity
    Elements with attribute values less than 1

Block formatting context

Block formatting context (

Block Formatting Context, BFC
) Is part of the visual CSS rendering of the Web page, the area where the layout process of the block box occurs, and the area where the floating element interacts with other elements.

Will create a block formatting context:

  • Root element (
    <html>
    )
  • Floating elements (elemental
    float
    Is not
    none
    )
  • Absolutely positioned elements (
    The position of the element is absolute or fixed
    )
  • Inline block element (element
    display is inline-block
    )
  • Table cell (element
    display is table-cell
    , HTML table cells default to this value)
  • Table title (element's
    display is table-caption
    , HTML table title defaults to this value)
  • contain
    Value is
    layout, content or paint
    Elements
  • Elastic element (
    display is flex or inline-flex
    Direct children of the element)
  • Grid element (
    display is grid or inline-grid
    Direct children of the element)

use

overflow: auto

Create one that will contain this float

BFC
, The usual practice is to set the parent element
overflow: auto
Or set other non-default
overflow: visible
Value.

Set up

overflow: auto
Create a new
BFC
To include this float. our
<div>
The element now becomes a mini layout in the layout. Any child elements will be included.

CSS flexible box layout

This property is shorthand for the following CSS properties:

  • flex-grow
  • flex-shrink
  • flex-basis

flex-shrink
Attribute specified
flex
The shrinking rule of the element.
flex
The element shrinks only when the sum of the default width is greater than the container, and the shrinkage size is based on
flex-shrink
Value.

flex-shrink: 2; flex-shrink: 0.6; /* Global values */ flex-shrink: inherit; flex-shrink: initial; flex-shrink: unset Copy code

flex-grow
Set up a
flex
Item main size
flex
Growth factor. It specifies
flex
How much space remaining in the container should be allocated to the project (
flex
Growth factor).

The main size is the width or height of the item, depending on

flex-direction
value.

flex-basis
Specified
flex
The initial size of the element in the main axis direction. If not using
box-sizing
If you change the box model, then this attribute is determined
flex
The content box of the element (
content-box
)size of.

flex-wrap
Specify
flex
Whether the element is displayed in a single line or in multiple lines. If line wrapping is allowed, this attribute allows you to control the stacking direction of the lines.

order
The attribute specifies the order in which the scalable items in the flexible container are laid out. Elements follow
order
Layout is performed in increasing order of the value of the attribute. Have the same
order
The elements of the attribute value are laid out in the order in which they appear in the source code.

flex-flow
Attributes are
flex-direction
with
flex-wrap
Shorthand for.

flex-direction: row flex-wrap: nowrap Copy code

Alignment properties

align-content
Properties set how the browser allocates space between and around content items along the vertical axis of the flexible box layout and the main axis of the grid layout.

/* Basic position alignment*/ /*align-content does not use left and right values*/ align-content: center;/* Place the item at the midpoint*/ align-content: start;/* Place the item first*/ align-content: end;/* Place the item last*/ align-content: flex-start;/* Place flex elements from the starting point*/ align-content: flex-end;/* Place flex elements from the end point*/ /* Default alignment*/ align-content: normal; /*Baseline alignment*/ align-content: baseline; align-content: first baseline; align-content: last baseline; /* Distributed alignment*/ align-content: space-between;/* Distribute items evenly The first item is flush with the starting point, The last item is flush with the end point*/ align-content: space-around;/* Distribute items evenly The project has half the size of space at both ends*/ align-content: space-evenly;/* Distribute items evenly There is equal space around the project*/ align-content: stretch;/* Distribute items evenly Stretch the'auto'-sized item to fill the container*/ /* Overflow alignment*/ align-content: safe center; align-content: unsafe center; /* Global attributes*/ align-content: inherit;/* inherit*/ align-content: initial;/* initial value*/ align-content: unset;/* not set*/ Copy code

align-items

Example:

align-items: stretch; align-items: center; align-items: start; align-items: end; Copy code

align-self: stretch;
The effect is as follows:

align-self: center;
The effect is as follows:

align-self: start;
The effect is as follows:

align-self: end;
The effect is as follows:

justify-content

justify-content: center;/* Arrange in the center*/ justify-content: start;/* Pack items from the start */ justify-content: end;/* Pack items from the end */ justify-content: flex-start;/* Arrange from the beginning of the line*/ justify-content: flex-end;/* Arrange from the end of the line*/ justify-content: left;/* Pack items from the left */ justify-content: right;/* Pack items from the right */ justify-content: space-between;/* Arrange each element evenly The first element is placed at the start point, and the last element is placed at the end point*/ justify-content: space-around;/* arrange each element evenly Allocate the same space around each element*/ justify-content: space-evenly;/* arrange each element evenly The interval between each element is equal*/ justify-content: stretch;/* arrange each element evenly 'auto'-sized elements will be stretched to fit the size of the container*/ Copy code

place-content
Attributes are
align-content
with
justify-content
Shorthand for

animation

  • animation-name
  • animation-duration
  • animation-timing-function
  • animation-delay
  • animation-iteration-count
  • animation-direction
  • animation-fill-mode
  • animation-play-state
animation: 3s ease-in 1s infinite reverse both running slidein; animation: 3s linear 1s infinite running slidein; animation: 3s linear 1s infinite alternate slidein; animation: .5s linear 1s infinite alternate slidein; @keyframes slidein { from {transform: scaleX(0);} to {transform: scaleX(1);} } Copy code
  • animation-name: none
  • animation-duration: 0s
  • animation-timing-function: ease
  • animation-delay: 0s
  • animation-iteration-count: 1
  • animation-direction: normal
  • animation-fill-mode: none
  • animation-play-state: running

Unit of length

There are two types of length in css: relative length and absolute length. The absolute length does not depend on any other measures. The absolute measurement maintains its length regardless of the environment in which it is applied.

The relative length depends on the environment in which it is used, such as the screen resolution of a computer monitor or the size of the font.

The absolute length is defined according to actual units, such as inches, centimeters, and points.

The length unit is divided into relative length unit and absolute length unit: relative/absolute

  • Relative length unit. Relative length unit points: relative font length unit and relative viewing area length unit
  • Relative font length unit,
    Such as em and ex, as well as css3 rem and ch
  • Relative viewport length unit, such as
    vh, vw, vmin, vmax
  • Absolute length unit, common
    px,pt,cm,mm,pc

css
Unit in:

time unit

s,ms
, Angle unit
deg,rad
, Length unit
px,em

%
Not a unit of length

Selector: 1, class selector, 2, ID selector, 3, attribute selector, 4, pseudo-class selector, 5, pseudo-element selector.

:first-child :last-child ::first-line ::first-letter ::before ::after Copy code

Relationship selector: 1, descendant selector, 2, adjacent descendant selector, 3, sibling selector, 4, adjacent sibling selector.

rule:

@

@ Some of the rules are defined by the rules of the @ character began as @media, @ font-face, @page , @support copy the code

Block-level elements and

display is block
The element is not a concept.

so, clear float:

.clear:after { content:'', display: table;//can be block, list-item clear: both; } Copy code

Do not use

list-item
Yes:

  1. 1. it has more characters
  2. Unwanted bullets will appear
  3. IE browser does not support pseudo-element
    display
    Refers to
    list-item
    , Mainly because of poor compatibility. For IE browser, common element settings
    display:list-item
    Effective but
    :before/:after
    The pseudo-element is invalid.

The block-level box is responsible for the structure, and the inline box is responsible for the content.

The default display of a tag element is inline, set display: block to block, and then

width: 100%
There is no problem.

box-sizing

box-sizing
Box size,
width
The details of the role,
box-sizing
The role of the attribute is to change
width
The details of the role. The 4 boxes of the inner box:

  1. content box
  2. padding box
  3. border box
  4. margin box

By default, width is used for

content box
Up,
box-sizing
The role of
width
The box of effect becomes several others.

Theoretically written:

.box1 {box-sizing: content-box;} .box2 {box-sizing: padding-box;} .box3 {box-sizing: border-box;} .box4 {box-sizing: margin-box;} Copy code

But you can only write the following:

.box1 {box-sizing: content-box;}//default value .box2 {box-sizing: padding-box;}//used to support .box3 {box-sizing: border-box;}//Support .box4 {box-sizing: margin-box;}//never supported Copy code

The practice of global reset is not recommended. This is easy to produce unnecessary consumption, this approach does not solve all problems.

*
Try not to use wildcards, because it will select all tag elements. For ordinary inline elements,
box-sizing
No matter what the value is, it has no effect on its rendering performance. There are also some elements, the default
box-sizing
Just
border-box
, So there is no necessary consumption.

Internet
working principle

What happens when you enter the Internet address in the browser:

  1. Enter www address in the browser
  2. The browser interacts with the HTTP server at that address
  3. HTTP
  4. HTTP web
  5. HTTP Web

web http internet HTTP HTTP web

HTTP HTML web

  • The value can be a keyword, length, color, string, integer, real, or URL.
  • The em measurement is best used for screen layout.
  • URIs are used to include style sheets and background images in CSS.
  • You can use the style attribute to directly include styles inline in HTML elements.

Selector

  • Class and ID selector
  • Universal selector
  • Descendant selector
  • Direct child selector
  • Adjacent selector
  • Attribute selector
  • Pseudo-element
  • Pseudo-class

Selection based on attribute value

The attribute value selector applies style declarations based on the existence and value of the attribute.

input[type="text"]{ background: blue; color: white; border: 3px solid royalblue; } <input type="text" name="first_name" value="name" size="25"/> Copy code

Attribute substring selector

A character string that appears in another character string is called a character string.

a[href^="ftp://"] { background: blue; color: white; border: 3px solid royalblue; } <a href="ftp://ftp.example.com"/>dadaqianduan.cn</a> Copy code

Pseudo-classes: Pseudo-classes are used to represent dynamic events, state changes, or situations that cannot be easily implemented in the document by other methods. It may be the user's mouse hovering or clicking on an element. Pseudo-classes apply styles to the target element in a special state.

Dynamic pseudo-class

  • :link
    , Which means a hyperlink that has not been visited
  • :visited
    , Which means the hyperlink has been visited
  • :hover
    , Which means that the mouse pointer is currently resting on the element
  • :active
    , Indicating that the user is clicking on the element
a:link { color: red; } a:visited { color: yellow; } Copy code

:first-child
Structured pseudo-classes are only used when one element is the first child element of another element.

Text attributes

  • letter-spacing
    Attributes and ways to use it to increase and decrease the letter spacing of words
  • word-spacing
    Attributes and methods of using it to increase and decrease the spacing between words in sentences
  • text-indent
    Properties and methods of using it to control text indentation in paragraphs
  • text-align
  • text-decoration
  • text-transform
  • white-space
  1. letter-spacing
letter-spacing: normal;
  1. word-spacing
word-spacing: normal;
  1. text-indent
  2. text-align
  3. text-decoration
  4. text-transform
#capitalize { text-transform: capitalize; } #uppercase { text-transform: uppercase; } #lowercase { text-transform: lowercase; }
  1. white-space
    web

  1. font-family
  2. font-style
  3. font-weight
  4. font-size

css overflow overflow

overflow: visible | hidden | scroll | auto

div { width: 0; border: 10px solid; border-color: #f30 transparent transparent; }

<style type="text/css"> .div5 { width: 0; border: 10px solid; border-color: #f30 transparent transparent; } .div1 { width: 10px; height: 10px; border: 10px solid; border-color: #f30 transparent transparent; } .div2 { width: 10px; height: 10px; border: 10px solid; border-color: #f30 #00f #396 #0f0; } .div3 { width: 0; border-width: 10px 20px; border-style: solid; border-color: #f30 transparent transparent; } .div4 { width: 0; border-width: 10px 20px; border-style: solid; border-color: #f30 #f30 transparent transparent; } </style>

css

  • line-height
  • vertical-align

JavaScript

const btn = document.querySelector('button'); btn.onclick = function() { const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')'; document.body.style.backgroundColor = rndCol; }

Array

var fruits = ['Apple', 'Banana']; console.log(fruits.length); //2

var first = fruits[0]; //Apple var last = fruits[fruits.length - 1]; //Banana

fruits.forEach(function (item, index, array) { console.log(item, index); }); //Apple 0 //Banana 1

var newLength = fruits.push('Orange'); //newLength:3; fruits: ["Apple", "Banana", "Orange"]

var last = fruits.pop();//remove Orange (from the end) //last: "Orange"; fruits: ["Apple", "Banana"];

var first = fruits.shift();//remove Apple from the front //first: "Apple"; fruits: ["Banana"];

var newLength = fruits.unshift('Strawberry')//add to the front //["Strawberry", "Banana"];

fruits.push('Mango'); //["Strawberry", "Banana", "Mango"] var pos = fruits.indexOf('Banana'); //1

var shallowCopy = fruits.slice();//this is how to make a copy //["Strawberry", "Mango"]

Array.prototype.pop()

Array.prototype.push()

Array.prototype.reverse()

Array.prototype.shift()

Array.prototype.sort()

Array.prototype.splice()

Array.prototype.unshift()

Array.prototype.concat()

Array.prototype.join()

Array.prototype.slice()

Array.prototype.toString()
Object.prototype.toString()

Array.prototype.indexOf()
-1

Array.prototype.lastIndexOf()
-1

Array.prototype.forEach()

Array.prototype.every()
true false

Array.prototype.some()
true false

Array.prototype.filter()
true

Array.prototype.map()

Array.prototype.reduce()
reduce()
reducer
( )

const array1 = [1, 2, 3, 4]; const reducer = (accumulator, currentValue) => accumulator + currentValue; //1 + 2 + 3 + 4 console.log(array1.reduce(reducer)); //expected output: 10 //5 + 1 + 2 + 3 + 4 console.log(array1.reduce(reducer, 5)); //expected output: 15

Array.prototype.reduceRight()
reduceRight()
accumulator

const array1 = [[0, 1], [2, 3], [4, 5]].reduceRight( (accumulator, currentValue) => accumulator.concat(currentValue) ); console.log(array1); //expected output: Array [4, 5, 2, 3, 0, 1]

Boolean

Boolean

0 -0 null false NaN undefined
""
false

undefined null
true

var x = new Boolean(false); if (x) { // } var x = false; if (x) { // } var x = Boolean(expression); // var x = !!(expression); // var x = new Boolean(expression);//

Boolean.prototype.toString()
"true" "false"
Object.prototype.toString()

Boolean.prototype.valueOf()
Boolean
Object.prototype.valueOf()

Date
JavaScript Date

new Date(); new Date(value); new Date(dateString); new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);

Date
new
let now = new Date();

new
Date

Date()

year monthIndex 0 1 11 12 date 1 1 hours (24 ) 0 minutes 01:10:00 0 seconds 01:10:00 0 milliseconds 0

Date.prototype.getDate()
1-31

Date.prototype.getDay()
0-6

Date.prototype.getFullYear()

Date.prototype.getHours()
0-23

Date.prototype.getMilliseconds()
0-999

Date.prototype.getMinutes()
0-59

Date.prototype.getMonth()
0-11

Date.prototype.getSeconds()
0-59

Date.prototype.getTime()
1970-1-1 00:00:00 UTC
1970-1-1 00:00:00 UTC

Function

Function.prototype.apply() Function.prototype.bind() Function.prototype.call() Function.prototype.toString()

JSON

JSON.parse() JSON.stringify()

Math

Math.abs(x) Math.acos(x) Math.acosh(x) Math.asin(x) Math.asinh(x) Math.atan(x) Math.atanh(x) Math.atan2(y, x) y/x Math.cbrt(x) Math.ceil(x) Math.clz32(x) 32 Math.cos(x) Math.cosh(x) Math.exp(x) Ex x E 2.718... Math.expm1(x) exp(x) - 1 Math.floor(x) Math.fround(x) Math.hypot([x[, y[, ]]]) Math.imul(x, y) 32 Math.log(x) e Math.log1p(x) 1 e Math.log10(x) 10 Math.log2(x) 2 Math.max([x[, y[, ]]]) Math.min([x[, y[, ]]]) Math.pow(x, y) y Math.random() 0 1 Math.round(x) Math.sign(x) 0 Math.sin(x) Math.sinh(x) Math.sqrt(x) Math.tan(x) Math.tanh(x) Math.toSource() "Math" Math.trunc(x)

Number

Number.isNaN() NaN Number.isFinite() Number.isInteger() number Number.parseFloat() parseFloat() Number.parseInt() parseInt()

Object

Object

Object.assign() Object.create() Object.defineProperty() Object.defineProperties() Object.entries() [key, value] Object.freeze() Object.getOwnPropertyDescriptor() Object.getOwnPropertyNames() Object.getOwnPropertySymbols() Object.getPrototypeOf() Object.is() Object.isExtensible() Object.isFrozen() Object.isSealed() Object.setPrototypeOf() [[Prototype]]

WeakMap

WeakMap
/

WeakSet

WeakSet

new WeakSet([iterable]);

instanceof

instanceof
prototype

function Car(make, model, year) { this.make = make; this.model = model; this.year = year; } const auto = new Car('2323', '2324', 1234); console.log(auto instanceof Car); //expected output: true console.log(auto instanceof Object); //expected output: true

typeof

typeof

console.log(typeof 42); //expected output: "number" console.log(typeof 'blubber'); //expected output: "string" console.log(typeof true); //expected output: "boolean" console.log(typeof undeclaredVariable); //expected output: "undefined"

new

new

function Car(make, model, year) { this.make = make; this.model = model; this.year = year; } const car1 = new Car('sdfs', 'sdfsd sdf', 2234); console.log(car1.make); //expected output: "Eagle"

Promises/A+

  • fulfill promise fulfill promise resolve
  • reject promise
  • eventual value promise promise promise
  • reason promise

var fs = require('fs') function writeFileAsync(fpath, data, cb) { fs.writeFile(fpath, data, function(err) { cb(err); }); } var fs = require('fs') var Promise = require('bluebird'); function writeFileAsync(fpath, data) { return new Promise(function(resolve, reject) { fs.writeFile(fpath, data, function(err){ if(err) reject(err) else resolve() }) }) }
// request(url, funcion(err, res, body) { if(err) handleError(err) fs.writeFile('1.txt', body, function(err) { if(err) handleError(err) request(url2, function(err, res, body) { if(err) handleError(err) }) }) }) //Promise request(url) .then(function(result) { return wirteFileAsync('1.txt', result) }) .then(function(result) { return request(url2) }) .catch(function(e){ handleError(e) })

function red() { console.log('red'); } function green() { console.log('green'); } function yellow() { console.log('yellow'); } var tic = function(timer, cb) { return new Promise(function(resolve, reject) { setTimeout(function(){ cb(); resolve(); },timer); }; }; var d = new Promise(function(resolve, reject){resolve();}); var step = function(def) { def.then(function() { return tic(3000, red); }).then(function() { return tic(2000, green); }).then(function() { return tic(1000, yellow); }); } var d = new Promise(function(resolve, reject) {resolve();}); var step = function(def){ while(true) { def.then(function() { return tic(3000, red); }).then(function() { return tic(2000, green); }).then(function() { return tic(1000, yellow); }); } } var d = new Promise(function(resolve, reject) { resolve();}); var step = function(def) { def.then(function() { return tic(3000, red); }).then(function() { return tic(2000, green); }).then(function() { step(def); }); }

var tic = function(timmer, str){ return new Promise(function(resolve, reject) { setTimeout(function() { console.log(str); resolve(1); }, timmer); }); }; function *gen(){ yield tic(3000, 'red'); yield tic(1000, 'green'); yield tic(2000, 'yellow'); } var iterator = gen(); var step = function(gen, iterator){ var s = iterator.next(); if (s.done) { step(gen, gen()); } else { s.value.then(function() { step(gen, iterator); }); } } step(gen, iterator);
var promise = new Promise(function(resolve) { resolve(42); }); promise.then(function(value) { console.log(value); }).catch(function(error) { console.log(error); });

getAsync("file.txt", function(error, result) { if(error){// throw error; } // });

Promise

var promise = getAsyncPromise('fileA.txt'); promise.then(function(result) { // }).catch(function(error) { // });

Constructor

Promise
XMLHttpRequest
Promise
promise

promise
new
Promise

var promise = new Promise(function(resolve, reject) { // // resolve reject });
promise.then(onFulfilled, onRejected)

resolve
( )
onFulfilled

reject
( )
onRejected

Promise

new Promise promise

"has-resolution" - Fulfilled
resolve
( )
onFulfilled

"has-rejection" - Rejected
reject
( )
onRejected

"unresolved" - Pending
resolve
reject
promise

promise
Pending
Fulfilled
Rejected
promise

Promise
Event
.then

XHR promise

function getURL(URL) { return new Promise(function (resolve, reject) { var req = new XMLHttpRequest(); req.open('GET', URL, true); req.onload = function() { if(req.status === 200) { resolve(req.responseText); }else{ reject(new Error(req.statusText)); } }; req.onerror = function() { reject(new Error(req.statusText)); }; req.send(); }); } // xxx var URL = "http://x'x'x.org/get"; getURL(URL).then(function onFulfilled(value){ console.log(value); }).catch(function onRejected(error){ console.error(error); });
Promise.resolve(42).then(function(value){ console.log(value); });
var promise = new Promise(function (resolve){ console.log("inner promise");//1 resolve(42); }); promise.then(function(value){ console.log(value);//3 }); console.log("outer promise");//2 nner promise//1 outer promise//2 42 //3

function taskA() { console.log("Task A"); } function taskB() { console.log("Task B"); } function onRejected(error) { console.log("Catch Error: A or B", error); } function finalTask() { console.log("Final Task"); } var promise = Promise.resolve(); promise .then(taskA) .then(taskB) .catch(onRejected) .then(finalTask); Task A Task B Final Task

AMD CMD

  • CMD AMD
  • AMD CMD

AMD CMD node CommonJS

CommonJS

AMD

  1. CommonJS ES6
  2. CommonJS ES6

CommonJS module.exports ES6

CommonJS

  • Chrome Dev Tool
  • Cmd + Shift + P or Ctrl + Shift + P ;
  • Coverage

Array.includes

function test(fruit) { if (fruit == 'apple' || fruit == 'strawberry') { console.log('red'); } }

function test(fruit) { // const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries']; if (redFruits.includes(fruit)) { console.log('red'); } }

return

function test(fruit, quantity) { const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries']; // 1 fruit if (fruit) { // 2 if (redFruits.includes(fruit)) { console.log('red'); // 3 10 if (quantity > 10) { console.log('big quantity'); } } } else { throw new Error('No fruit!'); } } // test(null);// No fruits test('apple');// red test('apple', 20);// red big quantity

/* return */ function test(fruit, quantity) { const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries']; // 1 if (!fruit) throw new Error('No fruit!'); // 2 if (redFruits.includes(fruit)) { console.log('red'); // 3 10 if (quantity > 10) { console.log('big quantity'); } } }

/* return */ function test(fruit, quantity) { const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries']; if (!fruit) throw new Error('No fruit!');// 1 if (!redFruits.includes(fruit)) return; // 2 fruit return console.log('red'); // 3 if (quantity > 10) { console.log('big quantity'); } }

JavaScript

null/undefined

function test(fruit, quantity) { if (!fruit) return; const q = quantity || 1;// quantity 1 console.log(`We have ${q} ${fruit}!`); } // test('banana');//We have 1 banana! test('apple', 2);//We have 2 apple!

function test(fruit, quantity = 1) {//i quantity 1 if (!fruit) return; console.log(`We have ${quantity} ${fruit}!`); } // test('banana');//We have 1 banana! test('apple', 2);//We have 2 apple!
function test(fruit) { // fruit.name if (fruit && fruit.name) { console.log (fruit.name); } else { console.log('unknown'); } } // test(undefined);//unknown test({ });//unknown test({ name: 'apple', color: 'red' });//apple

// name // {} function test({name} = {}) { console.log (name || 'unknown'); } // test(undefined);//unknown test({ });//unknown test({ name: 'apple', color: 'red' });//apple

// lodash _.get() function test(fruit) { console.log(_.get(fruit, 'name', 'unknown');// name unknown } // test(undefined);//unknown test({ });//unknown test({ name: 'apple', color: 'red' });//apple

Map/Object
Switch

function test(color) { // switch case switch (color) { case 'red': return ['apple', 'strawberry']; case 'yellow': return ['banana', 'pineapple']; case 'purple': return ['grape', 'plum']; default: return []; } } // test(null);//[] test('yellow');//['banana', 'pineapple']

// const fruitColor = { red: ['apple', 'strawberry'], yellow: ['banana', 'pineapple'], purple: ['grape', 'plum'] }; function test(color) { return fruitColor[color] || []; }
// Map const fruitColor = new Map() .set('red', ['apple', 'strawberry']) .set('yellow', ['banana', 'pineapple']) .set('purple', ['grape', 'plum']); function test(color) { return fruitColor.get(color) || []; }
const fruits = [ { name: 'apple', color: 'red' }, { name: 'strawberry', color: 'red' }, { name: 'banana', color: 'yellow' }, { name: 'pineapple', color: 'yellow' }, { name: 'grape', color: 'purple' }, { name: 'plum', color: 'purple' } ]; function test(color) { // Array filter return fruits.filter(f => f.color == color); }

Array.every
Array.some
/

const fruits = [ { name: 'apple', color: 'red' }, { name: 'banana', color: 'yellow' }, { name: 'grape', color: 'purple' } ]; function test() { let isAllRed = true; // for (let f of fruits) { if (!isAllRed) break; isAllRed = (f.color == 'red'); } console.log(isAllRed);//false }

const fruits = [ { name: 'apple', color: 'red' }, { name: 'banana', color: 'yellow' }, { name: 'grape', color: 'purple' } ]; function test() { // const isAllRed = fruits.every(f => f.color == 'red'); console.log(isAllRed);//false }

Array.some

const fruits = [ { name: 'apple', color: 'red' }, { name: 'banana', color: 'yellow' }, { name: 'grape', color: 'purple' } ]; function test() { // const isAnyRed = fruits.some(f => f.color == 'red'); console.log(isAnyRed);//true }

Spread operator

const favoriteFood = ['Pizza', 'Fries', 'Swedish-meatballs']; console.log(...favoriteFood); //Pizza Fries Swedish-meatballs

for of

const toolBox = ['Hammer', 'Screwdriver', 'Ruler'] for(const item of toolBox) { console.log(item) } //Hammer //Screwdriver //Ruler

Includes()

const garge = ['BMW', 'AUDI', 'VOLVO']; const findCar = garge.includes('BMW'); console.log(findCar); //true

const arr = [11, 22, 33, 44, 55, 66]; //truncanting arr.length = 3; console.log(arr);//=> [11, 22, 33] //clearing arr.length = 0; console.log(arr);//=> [] console.log(arr[2]);//=> undefined

(

destructuring
)

doSomething({ foo: 'Hello', bar: 'Hey!', baz: 42 }); function doSomething(config) { const foo = config.foo !== undefined ? config.foo : 'Hi'; const bar = config.bar !== undefined ? config.bar : 'Yo!'; const baz = config.baz !== undefined ? config.baz : 13; //... }

function doSomething({ foo = 'Hi', bar = 'Yo!', baz = 13 } = {}) { //... }

async/await
await
async

await Promise.all([anAsyncCall(), thisIsAlsoAsync(), oneMore()])

(

pure
)

const pureObject = Object.create(null); console.log(pureObject);//=> {} console.log(pureObject.constructor);//=> undefined console.log(pureObject.toString);//=> undefined console.log(pureObject.hasOwnProperty);//=> undefined

// const arr = [11, [22, 33], [44, 55], 66]; const flatArr = [].concat(...arr);//=> [11, 22, 33, 44, 55, 66]

unction flattenArray(arr) { const flattened = [].concat(...arr); return flattened.some(item => Array.isArray(item)) ? flattenArray(flattened) : flattened; } const arr = [11, [22, 33], [44, [55, 66, [77, [88]], 99]]]; const flatArr = flattenArray(arr); //=> [11, 22, 33, 44, 55, 66, 77, 88, 99]

Array.prototype

Array.prototype
Array
Array

/* JavaScript first() */ if(!Array.prototype.first) { Array.prototype.first = function() { console.log(` JavaScript first() `); return this[0]; } }
Array.isArray(Array.prototype); //true

-

Array.prototype.pop() Array.prototype.push() Array.prototype.reverse() Array.prototype.shift() Array.prototype.sort() Array.prototype.splice() Array.prototype.unshift()

Array.prototype.concat() Array.prototype.join() Array.prototype.slice() Array.prototype.toString() Object.prototype.toString() Array.prototype.indexOf() -1 Array.prototype.lastIndexOf() -1

Array.prototype.forEach()

Array.from()

Array.from()

console.log(Array.from('foo')); //expected output: Array ["f", "o", "o"] console.log(Array.from([1, 2, 3], x => x + x)); //expected output: Array [2, 4, 6]

Array.from(arrayLike[, mapFn[, thisArg]])

String

Array.from('foo'); //[ "f", "o", "o" ]

Set

const set = new Set(['foo', 'bar', 'baz', 'foo']); Array.from(set); //[ "foo", "bar", "baz" ]

arguments

function f() { return Array.from(arguments); } f(1, 2, 3); //[ 1, 2, 3 ]

function combine(){ let arr = [].concat.apply([], arguments); // return Array.from(new Set(arr)); } var m = [1, 2, 2], n = [2,3,3]; console.log(combine(m,n)); //[1, 2, 3]

Array.isArray()

Array.isArray()
Array

Array.isArray([1, 2, 3]); //true Array.isArray({foo: 123}); //false Array.isArray("foobar"); //false Array.isArray(undefined); //false

instanceof isArray

Array
,
Array.isArray
instanceof
,
Array.isArray
iframes
.

var iframe = document.createElement('iframe'); document.body.appendChild(iframe); xArray = window.frames[window.frames.length-1].Array; var arr = new xArray(1,2,3);//[1,2,3] //Correctly checking for Array Array.isArray(arr); //true //Considered harmful, because doesn't work though iframes arr instanceof Array;//false

Polyfill

if (!Array.isArray) { Array.isArray = function(arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; }

Array.of()

Array.of()

Array.of()
Array
Array.of(7)
7
Array(7)
7 7 (
empty
) 7
undefined

Array.of(7); //[7] Array.of(1, 2, 3);//[1, 2, 3] Array(7); //[ , , , , , , ] Array(1, 2, 3); //[1, 2, 3]

Array.of(element0[, element1[, ...[, elementN]]])

Array.of(1); //[1] Array.of(1, 2, 3); //[1, 2, 3] Array.of(undefined);//[undefined]

if (!Array.of) { Array.of = function() { return Array.prototype.slice.call(arguments); }; }

get Array[@@species]

Array[@@species]
Array

Array[Symbol.species]

Array

species
Array

species
, Array
Array:

Array[Symbol.species];//function Array()

JavaScript

function init() { var name = "Mozilla";//name init function displayName() {//displayName() alrt(name);// } displayName(); } init();

lexical

function makeFunc() { var name = "Mozilla"; function displayName() { alrt(name); } return displayName; } var myFunc = makeFunc(); myFunc();

//add5 add10 function makeAdder(x) { return function(y) { return x + y; }; } var add5 = makeAdder(5); var add10 = makeAdder(10); console.log(add5(2)); //7 console.log(add10(2));//12

function MyObject(name, message) { this.name = name.toString(); this.message = message.toString(); this.getName = function() { return this.name; }; this.getMessage = function() { return this.message; }; } function MyObject(name, message) { this.name = name.toString(); this.message = message.toString(); } MyObject.prototype = { getName: function() { return this.name; }, getMessage: function() { return this.message; } }; function MyObject(name, message) { this.name = name.toString(); this.message = message.toString(); } MyObject.prototype.getName = function() { return this.name; }; MyObject.prototype.getMessage = function() { return this.message; };

JavaScript
object
__proto__
prototype
(
__proto__
)
null
null

JavaScript
Object

JavaScript

ECMAScript
someObject.[[Prototype]]
someObject
ECMAScript 6
[[Prototype]]
Object.getPrototypeOf()
Object.setPrototypeOf()
JavaScript
__proto__

// o a b let f = function () { this.a = 1; this.b = 2; } /* function f() { this.a = 1; this.b = 2; } */ let o = new f();//{a: 1, b: 2} // f f.prototype.b = 3; f.prototype.c = 4; // f f.prototype = {b:3,c:4}; //o.[[Prototype]] b c // ( o.__proto__ o.constructor.prototype) //o.[[Prototype]].[[Prototype]] Object.prototype. // o.[[Prototype]].[[Prototype]].[[Prototype]] null // null // null [[Prototype]] // : //{a:1, b:2} ---> {b:3, c:4} ---> Object.prototype---> null console.log(o.a);//1 //a o 1 console.log(o.b);//2 //b o 2 // 'b' // " (property shadowing)" console.log(o.c);//4 //c o //c o.[[Prototype]] 4 console.log(o.d);//undefined //d o //d o.[[Prototype]] //o.[[Prototype]].[[Prototype]] null // d undefined

var o = { a: 2, m: function(){ return this.a + 1; } }; console.log(o.m());//3 // o.m 'this' o. var p = Object.create(o); //p o p.a = 4;// p 'a' console.log(p.m());//5 // p.m 'this' p // p o m // 'this.a' p.a p 'a'

JavaScript

function doSomething(){} console.log( doSomething.prototype ); // //JavaScript var doSomething = function(){}; console.log( doSomething.prototype );

{ constructor: doSomething(), __proto__: { constructor: Object(), hasOwnProperty: hasOwnProperty(), isPrototypeOf: isPrototypeOf(), propertyIsEnumerable: propertyIsEnumerable(), toLocaleString: toLocaleString(), toString: toString(), valueOf: valueOf() } }

doSomething

function doSomething(){} doSomething.prototype.foo = "bar"; console.log( doSomething.prototype ); { foo: "bar", constructor: doSomething(), __proto__: { constructor: Object(), hasOwnProperty: hasOwnProperty(), isPrototypeOf: isPrototypeOf(), propertyIsEnumerable: propertyIsEnumerable(), toLocaleString: toLocaleString(), toString: toString(), valueOf: valueOf() } }

var o = {a: 1}; //o Object.prototype //o hasOwnProperty //hasOwnProperty Object.prototype // o Object.prototype hasOwnProperty //Object.prototype null // : //o ---> Object.prototype ---> null var a = ["yo", "whadup", "?"]; // Array.prototype //(Array.prototype indexOf, forEach ) // : //a ---> Array.prototype ---> Object.prototype ---> null function f(){ return 2; } // Function.prototype //(Function.prototype call, bind ) // : //f ---> Function.prototype ---> Object.prototype ---> null

function Graph() { this.vertices = []; this.edges = []; } Graph.prototype = { addVertex: function(v){ this.vertices.push(v); } }; var g = new Graph(); //g 'vertices' 'edges' // g g.[[Prototype]] Graph.prototype

Object.create

create

var a = {a: 1}; //a ---> Object.prototype ---> null var b = Object.create(a); //b ---> a ---> Object.prototype ---> null console.log(b.a);//1 ( ) var c = Object.create(b); //c ---> b ---> a ---> Object.prototype ---> null var d = Object.create(null); //d ---> null console.log(d.hasOwnProperty);//undefined, d Object.prototype

class

class, constructor static extends super

"use strict"; class Polygon { constructor(height, width) { this.height = height; this.width = width; } } class Square extends Polygon { constructor(sideLength) { super(sideLength, sideLength); } get area() { return this.height * this.width; } set sideLength(newLength) { this.height = newLength; this.width = newLength; } } var square = new Square(2);

+ + + +

Jeskson
( ) ( )

github
Star
github.com/webVueBlog/