# 1209 JS
例題6
```
window.addEventListener('DOMContentLoaded', function () {
fetch('https://pastleo-posts-api.herokuapp.com/api/posts')
.then(request => request.json())
.then(posts => {
const firstPost = posts[0]
const titleA = document.querySelector('.post-title')
const linkA = document.querySelector('.post-link')
titleA.textContent = firstPost.title
document.querySelector('.post-created-at').textContent = firstPost.created_at
document.querySelector('.post-author').textContent = (`BY ${firstPost.author}`)
document.querySelector('.post-description').textContent = firstPost.description
titleA.href = firstPost.url
linkA.href = firstPost.url
linkA.classList.remove('hidden')
})
})
```
* `.then(request => request.json())`是這兩三年才有的新寫法,下面為舊寫法
```
.then(function(response)){
return response.json()}
```
要在內容中加上字串用(`字串 ${變數}`),注意符號是 ` 不是 ‘
* title,created_at,author,description,url都是由API提供的項目,用document.querySelector選取html元素再用textContent代入,而url用href做連結
==================================
## CORS
* Access-Control-Allow-Methods
* Access-Control-Allow-Headers
* Access-Control-Allow-Origin: * 允許所有來源存取
以上三項預設都為關閉不會讓外部存取,要設定才會出現
================================
## this
```
<button id='plus'>cnt.plus</button>
<br>
<button id='plusArr'>cnt.plusArr</button>
<br>
<button id='cntObj-plus'>cntObj.plus</button>
<br>
<button id='cntObj-plusArr'>cntObj.plusArr</button>
```
```
class Cnt {
constructor(init) {
this.value = init
console.log(this.value, this)
}
plus() {
this.value += 1
console.log(this.value, this)
}
plusArr = () => {
this.value += 1
console.log(this.value, this)
}
}
const cnt = new Cnt(0)
const cntObj = {
value: 0,
plus: function() {
this.value += 1
console.log(this.value, this)
},
plusArr: () => {
this.value += 1
console.log(this.value, this)
}
}
window.addEventListener('DOMContentLoaded', function() {
cnt.plus()
cnt.plusArr()
cntObj.plus()
cntObj.plusArr()
document.getElementById('plus').addEventListener('click', cnt.plus)
document.getElementById('plusArr').addEventListener('click', cnt.plusArr)
document.getElementById('cntObj-plus').addEventListener('click', cntObj.plus)
document.getElementById('cntObj-plusArr').addEventListener('click', cntObj.plusArr)
})
```
================================
## Asynchronous / 非同步
* CALLBACK
* 問PROMISE 1500
* ASYNC/AWAIT 1508 1539
1615 9