node.js設計模式第一章總結

node.js設計模式(第二版) 第一章總結
1.let const
let塊級作用域

'use static'
if(true){
	let a = 1;
}
console.log(a);//報錯a沒有定義

const定義的變量不能被修改

const a = 1;
a = 2; //報錯Uncaught TypeError: Assignment to constant variable.

const定義對象,不能改變引用對象,可以改變引用對象內容

const a = {};
a.b = 1;//不會報錯
a = null;//會報錯

如果想定義不可更改的變量,可以使用Object.freeze()
const與let定義的變量不可以重名

var a;
const a;//報錯
let a;//報錯

2.箭頭函數

特點:簡單、箭頭函數與父親塊級作用域相同
1.不使用箭頭函數

function delayFunction(name){
	this.name = name;
}
delayFunction.prototype.delay = function(){
 	setTimeout(function(){
 		console.log('hello' + this.name);
	},500)
}
var b = new delayFunction('world');
b.delay()//輸出hello

此時this指向全局
2.使用箭頭函數

function delayFunction(name){
	this.name = name;
}
delayFunction.prototype.delay = function(){
	setTimeout(()=>{
		console.log('hello' + this.name);
	},500)
}
var b = new delayFunction('world');
b.delay()//輸出hello

箭頭函數爲父親塊級作用域,this指向b

3.類class

class Person{
	constructor(preName,name,age){
		this.preName = preName;
		this.name = name;
		this.age = age;
	}
	fullName(){
		return this.preName + this.name;
	}
}
class Police extends Person{
	constructor(preName,name,age,phone){
		super(preName,name,age);
		this.phone = phone;
	}
	fullInformation(){
		return this.preName + this.name + this.phone;
	}
}

4.key計算屬性

const name = '--webkit--'
const style = {
	[namespace + 'height'] : '300px',
}

5.新定義的getter與setter方法

var person = {
	name: 'fa',
	preName: 'dai',
	get fullname(){
		return this.preName + this.name;
	},
	set fullname(fullname){
		let parts = fullname.split(' ');
    	this.preName = parts[0];
    	this.name = parts[1];
	}
}
console.log(person.fullname);//daifa
console.log(person.fullname = 'ling jia');//lingjia
console.log(person.name);//ling
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章