Hello everyone, the editor is here to answer the following questions for you. What kind of pages is JavaScript mainly used to develop? What can JavaScript be used for? Let’s take a look today!
JavaScript learning
Introduction
JavaScript is a high-level scripting language that belongs to the Internet. It has been widely used in Web application development. It is often used to add various dynamic functions to web pages and provide users with smoother and more beautiful browsing effects. Usually JavaScript scripts are embedded in HTML to implement their own functions using the python for statement.
Composition
-
ECMAScript, describes the syntax and basic objects of the language.
-
Document Object Model (DOM) describes methods and interfaces for processing web content.
-
Browser Object Model (BOM), describes the methods and interfaces for interacting with the browser.
Operating Mode
-
It is an interpreted scripting language (the code is not precompiled).
-
It is mainly used to add interactive behaviors to HTML (an application under Standard Universal Markup Language) pages.
-
It can be directly embedded into HTML pages, but writing it as a separate js file facilitates the separation of structure and behavior.
-
Cross-platform feature, with the support of most browsers, it can run on multiple platforms (such as Windows, Linux, Mac, Android, iOS, etc.).
-
The JavaScript scripting language, like other languages, has its own basic data types, expressions and arithmetic operators, and the basic program framework of the program. JavaScript provides four basic data types and two special data types for processing data and text. Variables provide a place to store information, and expressions can complete more complex information processing.
Features
- scripting language
- object based
- Simple
- Dynamic
- cross-platform
Basic syntax
alert(): pop-up window document.write("xxx"):Console generation
Use alert less, it will block
Naming rules
Variables must start with a letter Variables can also start with $ and _ symbols (although this is not recommended) Variable names are case-sensitive (y and Y are different variables),
Grammar rules
output
console.log() console.err(): output error console. warn(); Pop up a warning var b=confirm("") pop-up box, whether to confirm, with confirmation, cancel document.getElementById("demo").innerHTML="hello":js output
Jump syntax
location.href="Link": Jump to a certain page prompt("Where are you from") pop-up window with input box
Data type
Value type (basic type): String, Number, Boolean, Null, Undefined, Symbol.
Reference data types: Object, Array, Function.
typeof(): View type
var length = 16; //Number assignment via numeric literal var points = x * 10; // Number assignment via expression literal var lastName = "Johnson"; // String assignment via string literal var cars = ["Saab", "Volvo", "BMW"]; // Array assignment via array literal var person = {firstName:"John", lastName:"Doe"}; // Object is assigned through object literal
Array definition and traversal
var arr=new Array(); arr[0]='Zhang San'; arr[1]='李思'; arr[2]='王五'; for(var i=0;i<arr.length;i + + ){ document.write(arr[i] + '<br />') }
Object
Key-value pairs are usually written as name : value (key and value are separated by colon).
//Define object var stu={ username:'chen', password:'123456', id: 1, full:function(){ return this.username + this.password } }; document.write(stu.username) document.write(stu["password"] + "<br />") document.write(stu.full())
Variable declaration
- The lifetime of JavaScript variables begins when they are declared.
- Local variables will be deleted after the function is run.
- Global variables will be deleted after the page is closed.
Event
HTML events can be browser actions or user actions.
The following are examples of HTML events:
- HTML page completes loading
- When HTML input field changes
- HTML button clicked
Event | Description |
---|---|
onchange | HTML element changes |
onclick | User clicks on HTML element |
onmouseover | The user moves the mouse on an HTML element |
onmouseout | The user moves the mouse off an HTML element |
onkeydown | The user pressed a keyboard key |
onload | The browser has completed loading the page |
String
The string object is an object type
Don’t create String objects. It slows down execution and may have other side effects
=== is absolute equality, that is, both data types and values must be equal.
conditional operator
variablename=(condition)?value1:value2 voteable=(age<18)?"Age is too young":"Age has reached";
Use the constructor property to see if the object is an array (containing the string “Array”):
<p>Determine whether it is an array.</p> <p id="demo"></p> <> var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = isArray(fruits); function isArray(myArray) { return myArray.constructor.toString().indexOf("Array") > -1; } </>
Scope
If no variable is declared during the assignment operation, it will be automatically declared as a global variable and assigned.
Closure: When a variable inside a function is referenced by another function, the variable of this function will not be destroyed after execution.
Object-oriented
Objects are stored in the heap
Constructor creates object
Literal object creation: Create an object without properties and methods
student[name’]: Get the object name
Delete object
delete.student.age
Determine whether the value is inside
'name' in student t.hasOwnProperty('name')
Addresses are placed on the stack and objects are placed on the heap.
this keyword
Every time you call a function, an implicit parameter is passed into the function. This implicit parameter is this, and this points to an object.
The context object for function execution
The function is an object and stores the memory address.
Array-like
arguments: Get the parameters passed in, only used in functions, representing actual parameters, a pseudo array
Change the point of this
call/apply: Through call/apple, you can modify the point of this when calling the function
student.like.call(teacher,"sing","dance") student.like.apply(teacher,["sing","jump"]) < type="text/java"> var student={ name:"chen", like:function(){ console.log(this) console.log(this.name + "Like playing basketball") for(var i=0;i<arguments.length;i + + ){ console.log(this.name + arguments[i]) } } } var teacher={ name:"chao" } var fn=student.like //student.like() window.fn() fn.call(teacher) fn.apply(teacher) </>
bind changes this pointer
var student = { name: "student", like: function() { console.log(this.name + "Like playing basketball") }.bind(teacher) }
Create objects
Literal mode
var student = { name: "Xiao Ming", age: 16, school: "No.1 Middle School", like: function() { console.log(this.name + "Like playing basketball") } }
Factory mode
function Student(name,age,likename) { var student = { name: name, age: age, school: "No.1 Middle School", like: function() { console.log(this.name + likename) } } return student } var s1=Student("Xiaohong",18,"playing piano") console.log(s1) var s2=Student("Xiao Ming",20,"Playing table tennis") console.log(s2)
Constructor creates object
var t1=new Teacher()
class creates objects
class Cat{ //Define constructor constructor(name,color,likename) { this.name=name; this.color=color; this.like=function(){ console.log(this.color + "的" + this.name + "Like" + likename) } } } var c1=new Cat("Persian cat","white","hairball") console.log(c1)
Determine whether the created object is an instance
instanceof
Prototype prototype
<template> <div> <h1>Weather</h1> <h2>City: {<!-- -->{ city }}</h2> <h3>Temperature: {<!-- -->{ tmp }}℃</h3> <h3>Weather conditions: {<!-- -->{ cond }}</h3> <h3>Wind direction: {<!-- -->{ wind }}</h3> <h3>Weather index: {<!-- -->{ brf }}</h3> <h3>Update time: {<!-- -->{ time }}</h3> <router-link to="/about">Enter about</router-link> </div> </template> <> import axios from "axios"; export default { data() { return { city: null, tmp: null, wind: null, cond: null, brf: null, time: null, }; }, // asynchronous async beforeMount() { let key = "bd5c2bbed6ac44b9a504781e436299a8"; let httpUrl = `https://free-api.heweather.net/s6/weather/now?location=${this.$route.params.city} & amp;key=${key}`; let res = await axios.get(httpUrl); let data = res.data; //this.city = data.HeWeather6[0].basic.location; this.city = data.HeWeather6[0].basic.location; this.cond = data.HeWeather6[0].now.cond_txt; this.wind = data.HeWeather6[0].now.wind_dir; this.tmp = data.HeWeather6[0].now.tmp; this.time = data.HeWeather6[0].update.utc; let url = `https://free-api.heweather.net/s6/weather/lifestyle?location=${this.$route.params.city} & amp;key=${key}`; let res1 = await axios.get(url); let data1 = res1.data; this.brf = data1.HeWeather6[0].lifestyle[3].txt; console.log(res1); console.log(res); //console.log(res); //console.log(this.$route) }, }; </>
ES6
let and const solve the problem of var variable penetration and constant modification problem
arrow function rule
- remove function
- Add arrows after brackets
- If the logic code only has return, it can be omitted directly. (If you are logical, you cannot omit it)
- If there is only one parameter, you can omit the parentheses
es6 abbreviation
- Because the object is key:value exists
- If the names of the key and the variable are consistent, you can define them once.
- If value is a function, you can remove
:function
, leaving only ()
es6 object structure-actually a way to quickly obtain properties and methods
The map has its own loop and will backfill the processed value into the corresponding position.
<> var arr=[1,2,3,4,5,6] //map comes with loop var newArr=arr.map(function(el){ return el*2 }) console.log(newArr) </>
npm: node package manager,node package manager
effect:
- Quickly build nodejs project npm init
- Quickly install and depend on third modules
npm install -g cnpm –registry=https://registry.npm.taobao.org
Specify version: npm install [email protected]
Uninstall: npm uninstall xxx
Steps to switch to es5
- Install babel: npm install -g babel-cli
- Check the version number: babel –version
- Install babel converter: cnpm install –save-dev babel-preset-es2015
- Execution: babel src -d dist
Commons js specification
Import tool class
//Tool class const sum=function(a,b){ return a + b } const sub=function(a,b){ return a-b } const mul=function(a,b){ return a*b } const div=function(a,b){ return a/b } //Export for others to use module.exports={ sum:sum, sub:sub, mul:mul, div:div }
test
const m=require("./four arithmetic operations.js") console.log(m.sum(1,2))
es6
export default { getList() { console.log('Get data list 2') }, save() { console.log('Save data 2') } }
test
import user from "./userApi2.js" user.getList() user.save()
What is Webpack
Webpack is a front-end resource loading/packaging tool. It will perform static analysis based on module dependencies, and then generate corresponding static resources for these modules according to specified rules.
js packaging
const path = require("path"); //Node.js built-in module module.exports = { entry: './src/main.js', //Configure entry file output: { path: path.resolve(__dirname, './dist'), //Output path, __dirname: the path of the current file filename: 'bundle.js' //Output file } }
Command: webpack -w:listen
webpack -h:help
webpack.config.js
//Import path directory const path=require('path') //Define json packaging rules module.exports={ entry:"./src/main.js", output: { path:path.resolve(__dirname,"./dist"), filename:'bundle.js' }, module: { rules: [ { test: /\.css$/, //Packaging rules are applied to files ending with css use: ['style-loader', 'css-loader'] } ] } }
ame: the path where the current file is located
filename: bundle.js’ //Output file
}
}
Command: webpack -w:listen webpack -h:help webpack.config.js
//Import path directory
const path=require('path') //Define json packaging rules module.exports={ entry:"./src/main.js", output: { path:path.resolve(__dirname,"./dist"), filename:'bundle.js' }, module: { rules: [ { test: /\.css$/, //Packaging rules are applied to files ending with css use: ['style-loader', 'css-loader'] } ] } }
The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java Skill TreeHomepageOverview 139503 people are learning the system