雜項
hasOwnProperty方法
回傳物件屬性的"鍵"是否存在的判斷:
const obj ={}
obj.prop = 'exists'
console.log(obj.hasOwnProperty('prop') )
console.log(obj.hasOwnProperty('toString')) // false
Object.create
用Object.create建立物件,在原型中比new正統
Object.create與new運算符相似,差別在
Object.create不會執行建構函式
const PlayerPrototype = {
name: '',
toString() {
return 'Name: '+ this.name
}
}
const inori = Object.create(PlayerPrototype)
inori.name = 'iNori'
console.log(inori.toString())
模組(Module)樣式
這個樣式使用了IIFE
用來模擬物件中的私有成員上(私有屬性與方法)與公開成員
var Module = (function() {
// 以下的方法是私有的,但是可以被公開的函式存取
function privateFunc() { ... }
// 回傳要指定給模組的物件
return {
publicFunc: function() {
privateFunc() // publicFunc 可以直接存取 privateFunc
}
}
}())
柯里化(Currying)與部份應用(Partial application)
部份應用: 代表一個函式其中有部份的傳入值(一個或多個)被傳入,然後回傳一個已經有部份傳入值的函式。(部份帶入)
柯里:把原本多個傳入參數的函式,轉變為一次只傳入一個參數的函式,可以連續呼叫使用。(逐一帶入)
部份應用(Partial application)
//原本的函式
function add(x, y, z){
return x+y+z
}
//改寫1
function addXY(z){
return add(1, 2, z)
}
addXY(3)
//改寫2
function add(x, y, z){
return function(z){
return x+y+z
}
}
const addXY = add(1, 2)
addXY(3)
柯里化
//原本的函式
function add(x, y, z){
return x+y+z
}
//柯里化
function add(x, y, z){
return function(y){
return function(z){
return x + y + z
}
}
}
add(1)(2)(3)
展開運算符與其餘運算符
兩者符號相同都是...
展開運算符(Spread Operator)用於展開陣列
const params = [ "hello", true, 7 ]
const other = [ 1, 2, ...params ] // [ 1, 2, "hello", true, 7 ]
其餘運算符(Rest Operator)用在二個地方。
一個是傳入參數定義中。另一種情況是用在解構賦值時。
//傳入參數定義中
function sum(…numbers) {
const result = 0
numbers.forEach(function (number) {
result += number
})
return result
}
sum(1) // 1
sum(1, 2, 3, 4, 5) // 15
//陣列解構賦值
const [x, ...y] = [1, 2, 3]
console.log(x) //1
console.log(y) //[2,3]
//可以給定如果沒有賦到值時(對應的值不存在)的預設數值
const [missing = true] = []
console.log(missing)
//ES7語法:物件解構賦值
// key值相同就能賦值
let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }
console.log(x) // 1
console.log(y) // 2
console.log(z) // { a: 3, b: 4 }
// Spread Properties
let n = { x, y, ...z }
console.log(n) // { x: 1, y: 2, a: 3, b: 4 }
函式傳入參數定義中也可以使用解構賦值
//傳入沒有名稱的物件,直接解構
function func({a, b}) {
return a + b
}
func({a: 1, b: 2}) // 3
generator
可中斷的函數,且可恢復執行
每次執行一個區間的代碼,分段執行,且異步調用
遇到yield就停止,傳回執行結果
*表示此為generator
//例一
function* gen(){
yield 1
yield 2
return 3
}
//非回傳3,而是產生iterator object
let g=gen()
g.next() //{value:1,done:false}
g.next() //{value:2,done:false}
g.next() //{value:3,done:true}
g.next() //{value:undefined,done:true}
//例二
function* demo(){
yield a = yield Promise.resolve(1)
yield b = yield Promise.resolve(a+2)
yield c = yield Promise.resolve(3+b)
return c
}
Last updated
Was this helpful?