---
title: 20200903 Astro Camp javascript 泰安老師
tags: Astro Camp, javascript
---
# 20200903 Astro Camp javascript 泰安老師
[投影片連結!](https://bre.is/7mJFwSEe)
## ===Ruby===
getter
這個屬性開放外界讀取
```ruby=
def location
@location
end
```
setter
開放外界寫入
```ruby=
def location=(new_location)
# @location = new_location
end
```
在class 裡寫上
```ruby=
attr_accessor :location
# 相當於生出getter跟setter
```
```ruby=
attr_reader :location
# 相當於生出getter
```
```ruby=
attr_writer :location
# 相當於生出setter
```
## ===js===
```javascript=
// 建構式函式,相當於ruby 的initialize
function Car() { //建構式函式習慣大寫
this.location = [0, 0];
this.galine = 100;
}
let c = new Car()
console.log(c)
```
```javascript=
Car.prototype.drive = function(distance) {
console.log(this.location)
console.log(distance)
}
let c1 = new Car()
c1.drive([5, 5])
console.log(c1)
```
所謂的this
就是正在呼叫function的環境!
(誰去呼叫有this的函示,誰就是this)
```javascript=
var person = {
name: 'john',
eat: function(food) { console.log(`${this.name} eat some ${food}`)}
}
person.eat('rice')
//此時的 this 就是 person ,而person有eat方法
let e1 = person.eat;
e1('noddle') //此時呼叫funtion的地方是global,而他沒有eatz;
global.name = "bob"
e1('noddle')
```
若單純去呼叫,this 都是global,但是
可以用call
apply
```javascript=
var person = {
name: 'john',
eat: function(food, drink) {
console.log(`${this.name} eat some ${food}`)
console.log(`${this.name} drink some ${drink}`)
}
}
person.eat('rice', 'coke')
let e1 = person.eat;
e1('noddle', 'coke')
// global.name = "bob"
e1('noddle', 'coke')
e1.call({name: 'Julian'}, 'noddle', 'coke')
```
```javascript=
function warning(){
alert('Hey!!!! WTF')
alert('okay....')
}
// warning()
let btnEl = document.querySelector('#btn')
btnEl.addEventListener('click', warning);
//等於下面這行
btnEl.addEventListener('click', () => {
wraing();
});
```
closure
畫面上有5個btn,期望能按到哪個就可以console.log相對應的編號:
```javascript=
let els = document.querySelectorAll('.btn')
for(var i = 0; i < els.length; i++) {
// var f = () => {console.log(i)}
// var f = (i => () => console.log(i))(i)
function f(i) {
return function() {
console.log(i)
}
}
els[i].addEventListener('click', f)
}
```
```javascript=
//lazy function
let add3 = x => y => z => x + y + z
let firstStep = add3(10)
let secondStep = firstStep(20)
let result = secondStep(30)
console.log(result)
//簡化!
let newResult = add3(100)(200)(300)
console.log(newResult)
```
| map | filter | reduce |
| ------------------------- | ------------------------ | ----------- |
| 對array中每一個元素作處理 | 對每一個元素去判斷布林值 | 將array收合 |
| 長度、型別不變 | 長度會變 | 回傳一個值 |
用each的話 array固定從第一個開始跑。
用map的話 回傳的東西、計算的方式可能與array的順序無關,只要最後的東西符合規則就好。
result 會拿一個初始值(輸出值的型別跟他一樣),
reduce運算的identity
加:0
乘除:1
集合起來:[],{}
reduce 接收三個參數:
1. 要處理的東西
2. 處理東西的規則(function)
3. 起始值