const obj ={}
obj.prop = 'exists'
console.log(obj.hasOwnProperty('prop') )
console.log(obj.hasOwnProperty('toString')) // false
const PlayerPrototype = {
name: '',
toString() {
return 'Name: '+ this.name
}
}
const inori = Object.create(PlayerPrototype)
inori.name = 'iNori'
console.log(inori.toString())
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
//例一
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
}