JS basic
JS is OOScripting language.
JS on the client side access the DOM.
JS on the server side can communicate with databases.
Using <script type = "text/javascript" src="./index.js"></script>
to directly use the JS code.
DOM enables dynamically generate HTML code. Eg:document.getElementById().innerHTML() = ‘’.
var can start with $
,no number,no space. Camelcasing var.
var data = [];data.push(0),data.pop();
onkeypress/onChange事件
ES6
New features
arrow functions, import, const.
let a = 5 === var a = 5;
local scope vs global scope. {}.differenciate from closure.{work in its self scope}
`` as template string. ${}
[10,…a,50];spread operator concatenate.
function(…a){}, gathering all parameters into an array.
let [name,parent] = a;
()=>,no this contained. Annoynous function expression{
function() {};
}
.map(function)/filter(boolean test). string.repeat(50)/startsWith()/includes(). Safe integer: Number.isSafeInteger(number).
module: split code into file based on relevance. export default add; import add from “math.js”/import {multiply} from “math.js”.
Webpack & Babel
Using webpack(打包工具) && Babel to let JS be compatible with the browser. Basically they are transpilier, generate code to olderjs.webpack bundles multiple modules into one js file, come with dev-server, update timely.
npm install webpack –save-dev.
npm install babel-core babel-loader webpack-dev-server babel-preset-es2015 babel-polyfill –save-dev.
npm install –save-dev babel-preset-react.
webpack.config.js:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22module.exports = {
entry: ['babel-polyfill','./app/index.js'],
output:{
path:__dirname + '/build',
filename:'bundle.js'
},
module:{
loaders:[
{
loader:'babel-loader',
test:/\js$/,
exclude:/node_modules/
}
]
},
devServer:{
port: 3000,
contentBase:"./build",
inline:true // automatically update code
}
}
package.json:script:"build":"webpack"
. add "babel":{"presets":["es2015"] }
, "start": "webpack-dev-server"
.
Classes in ES6
- relate each other with Inheritence
- Defined with class keyword and assign data with constructor function.
- Use extends keyword to generate child classes. Child classes has all properties of parent classes. Use super(arg1, arg2) to use parent properties.
- Static methods in class. Can use all methods in this class using class name.
- Classes & Prototypes. Object-oriented programming:object hold data interact with each other. JS is not, prototypal inheritence model. Classes are extractions of prototypes. A prototype reveals object’s parent. All objects has prototypes(Date,array). Prototype chain: top is object.
- class.prototype.func = function(){}; add a new method to the class. prototypes are simply functions. Must use function to generate because ()=> has no this contained.
Data structure in ES6
- Set(). let a = new Set(can contain arg). a.add() can add all different var. a.has(). for(let element of a.values()){element+=1;}
- Map(). map.size(). key can be anything rather than object’s key can only be string. a.set(key,value)/get(key), a.has(). key can be object/function/string; for(let [key,value] of map.entries());
Closures
- Closures refers to functions that remember the environment they are created in and can reference independent variable within this env. Closures combine functions with environment within which we declare that function. 是函数独有的特性,普通block是可以引用到的。function内部的function/data 外部直接引用不到。
- Enables function factories: function return function. Enable private data, in js can’t do it directly, can emulate this behavior.
- Lexical scoping refers to function use a var to keep tracks of where it can access. All local var only lasts through the completion of function, but can use closures still access the data. eg: let fun = ()=>{a=2;let help=()=>{consoloe.log(a);}return help}; let ano = fun;ano() can access a.
- let addSurfix = (x)=>{ const concat = (y)=>{return y+x;} return concat;}. let addness = addSurfix(“ness”)(this will generate a function, concat).let h = addness(“happi), h() shows happiness.
Generators
- break typical run to complete model in normal functions. Generators can pause in the middle and resume later, with yield(),next(). Yield tells function to pause and return current state.
- enable construct control-flow functions and iterators. function* maker(){yield count+=3;} let ano = maker();ano.next().value;建立一个generator的实例。eg:help generate IDs/counter.
- Generator vs iterator, write your own iterator.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20const arrayIndex = (array) => {
let index = 0;
return {
next:()=>{
if(index < array.length()) {
let next = array[index];
index +=1;
return next;
}
}
}
}
let it = arrayIndex([1,2,3]);
console.log(it.next());
function* iterator = (array)=>{
yield* arguments;
}
const it = iterator([1,2,3]);
it.next().value;
Asynchronous programming & Promises
- Asynchronous programming divert block to event handler. Running on a looped engine, keeps a program running without block.
- Important reason: (1)User interfaces & browser are asynchrounous in nature. function diverted to handler and processed in background. Async enables interation with DB, API.
- Promises handles aync in ES6(before callback). Promises presented in 3 states:pending, fulfilled, rejected.
- resolve & reject represents handlers that gives a function to update the state of promise. reject means promise can’t determine a value. Accessing the promise data as consuming the process.Use a promise.then() which accepts function gets promise’s return value once it is fulfilled.
1
2
3
4
5
6
7
8
9
10let p = new Promise((resolve,reject)=>{
resolve('Resolved a promise');
});
p.then(respose=>console.log(response))//Consuming the processed data
.catch(err=>console.log(err));
// Promise doesn't resolved immediately
new Promsie(setTimeout(()=>resolve('dsad'),3000).then(response=>{});
console.log('after promise');
// Can still run the code after the promiseHTTP methods
Defines how data communicated through Internet.
- GET:retrieve data and has no side effect
- POST:add resources to server
- HEAD, DELETE, PATCH
fetch(url,{method:”GET”}), returns a promise containing the result of that call. .json() returns another promise contained in th returned result. .then(response=>response.json()).then(jsons=>console.log(jsons)).ES7 && ES8
ES7
- exponential operator,2**5-32.
- support for arrays. arr.includes(2) == true
npm install babel-preset-es2016 babel-preset-es2017
ES8 - access object manipulate with .values()+.entries()
let a ={‘a’:1,’b’:2};let keys = Object.keys(a)/values(a);
let entries = Object.entries(a);
for(let cur of entries) {cur[0]} - Async. don’t want logic to continue until get relavant data in functions. Use await to temprtial stop the execution of statements and logic until finishes returning a promises.
CSS3
column-count:3
column-rule:线型
column-gap:40px;之间的间距
z-index 属性设置元素的堆叠顺序。拥有更高堆叠顺序的元素总是会处于堆叠顺序较低的元素的前面。越大离用户越近。
.left {
float:left;
width:200px;
}
.right {
float:right;
width:200px;
}
.main {
margin-left:200px;
margin-right:200px;
}
{
position:absolute;
width:400px
height:400px;
top:50%;
left:50%;
margin-top:-200px;
margin-left:-200px;
}