刚接触js,比较新鲜的用法记录一下。
vscode Plugin live server
不用架设服务器,右键直接跑js代码,很方便。
function expressions
let square = ( x ) =>{
return x*x;
}
// the function is just one line of code with one parameter
let square=x=>x*x;
Array Filter Map Reduce
const numbers = [1,-1,2,3];
// filter
const filtered = numbers.filter(n=>n>=0);
// map
const items = filtered.map(n=>'<li>'+n+'</li>');
const html = items.join(''); // use '', default is ','
// reduce, to one value
// a = 1, c = -1 => a = 0
// a = 0, c = 2 => a = 2
// a = 2, c = 3 => a = 5
const sum = numbers.reduce(
(accumulator, currentValue) => accumulator + currentValue
);
function arguments
// spread operator
function displayColors(...colorArray){
for( let color of colorArray )
console.log( color );
}
displayColors('red','green','blue');
Array foreach
let planets = {'j','v','s','m'};
planets.forEach(displayElements);
// callback
function displayElements(e){
console.log(e);
}
// anonymous callback
planets.forEach((planet)=>{
console.log(planet);
});
// combine keys, room is a object
Object.keys(room).forEach(key=>{
let value = room[key];
console.log( key + value );
});
For loop comprehension
let numbers = [1,2,3,4,5];
let squared = [for(x of numbers) x*x]; // [1,4,9,,16,25]
destructuring
let statistics = [16,170,10];
let [age,height,grade] = statistics;
// object
let position = {x:120,y12};
let {x,y} = position; // two new variables
value or reference
let x = {value:10}; // x is an object, reference
let y = x;
x.value = 20;
console.log(y);
// function argument
let number = 10; // value
function increase( number ){
number ++;
}
increase(number);
console.log(number);
factory function or constructor function
建立对象的2种方式
// 1) factory function, camel notation
function createCircle( radius ){
return{
radius,
draw(){
console.log('draw circle');
}
}
}
// 2) constructor function, pascal notation
function Circle( radius ){
let defaultLoction = { x:0, y:0 }; // private
this.radius = radius;
this.draw = function(){
console.log('draw circle');
}
//return this; // new will do it for us.
}
const circle = new Circle(1);
clone 3 ways
3 种clone方法
//1)
for(let key in circle){another[key] = circle[key];}
//2)
const another = Object.assign({},circle);
//3)
const another = {...circle};
// assign
function animal( config ){
var newObject = {
legs:4,
eyes:2,
say:'huh',
speak(){
console.log( this, say);
}
};
Object.assign( newObject, config );
return newObject;
}
this
指向谁?
1)在method里,this是这个object
2)在function里(包含callback),this是global(window,global)
是1)还是2)?
const video = {
title:'abc',
tags:['a','b','c'],
showTags(){
this.tags.forEach(function(tag){ // 是1) 在method里, must write 'this' here.
console.log(this.title, tag); // 是2)在function里(包含callback),this is the param
}, this); // 是1) 在method里, pass this to function as param
}
}
closure
这些变量会和用到它的函数在一起,分配了内存空间可以使用。调试的时候可以看scope chain。
闭包和作用域不同
// factory function
function animal(){
let newObject, words;
function random(min,max){
return Math.floor(Math.random()*(max-min+1)) + min;
}
words = ['Food','Sleep','Play'];
function speak(){
let say = word[random(0,2)];
console.log(say);
}
newObject = {};
newObject.speak = speak; // newObject only has a function
return newObject;
}
let cat = animal();
// speak使用了animal function中的另外的东西,speak是public的,其他是private的
cat.speak();
prototype
function Animal(){
this.eyes = 2;
this.feet = 4;
}
// 如果要给Animal添加method就用一个叫做prototype的特殊属性
Animal.prototype.speak = () =>{
console.log('huh');
};
inheritance
class Monster {
constructor(hitPoints, scariness) {
this.name = 'Monster';
this.hitPoints = hitPoints;
this.scariness = scariness;
}
speak() {
console.log( `I'm a ${this.scariness}
scary ${this.name}
with ${this.hitPoints} hit points`
);}
attack(skill) {
console.log(`The ${this.name} attacks with ${skill}!`
); }
}
class Dragon extends Monster {
constructor(hitPoints, scariness, weapon) {
//call the parent class's constructor with `super`
super(hitPoints, scariness);
this.name = 'Dragon';
this.weapon = weapon;
}
breatheFire () {
//Call the parent class's `attack` method
super.attack(`flaming ${this.weapon}`);
}
}
Pormises
// 避免callback hell
function wait(duration = 0) {
return new Promise(resolve => setTimeout(resolve, duration));
}
wait(1000)
.then(()=> console.log('One'))
.then(()=> wait(1000))
.then(()=> console.log('Two'))
.then(()=> wait(1000))
.then(()=> console.log('Three'));
modules
// Animal.js
export default class {
constructor() {
this.legs = 4; this.eyes = 2; this.say = 'Huh?';
}
speak() {
console.log(this.say);
}
}
// main.js
import Animal from 'Animal';
var cat = new Animal();
cat.say = 'Meow!';
cat.speak();