JavaScript 用法舉例

剛接觸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();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章