Skip to content

Instantly share code, notes, and snippets.

View doug2k1's full-sized avatar

Douglas Matoso doug2k1

  • Campinas - SP - Brazil
View GitHub Profile
// the request:
// POST a new email address to my GitHub account
fetch('https://api.github.com/user/emails', { // the URI
method: 'POST', // the method
body: JSON.stringify(["[email protected]"]) // the body
})
.then(response => {
// we received the response and print the status code
console.log(response.status)
// return response body as JSON
// the request:
// try to GET an nonexistent URI
fetch('https://api.github.com/nonexistent-uri')
.then(response => {
if (response.ok) {
// we should not reach here
console.log('success')
} else {
console.log(response.status)
}
// requisição:
// não é preciso informar o método (GET é o padrão),
// nem cabeçalho ou corpo (requisição GET não precisa de corpo)
fetch('https://api.github.com/repos/facebook/react/releases/latest') // URI
.then(response => {
// recebemos a resposta e logamos o status
console.log(response.status)
// retorna o corpo da resposta em formato JSON
return response.json()
})
// requisição:
// adicionar um novo endereço de e-mail à minha conta do GitHub
fetch('https://api.github.com/user/emails', { // URI
method: 'POST', // método
body: JSON.stringify(["[email protected]"]) // corpo
})
.then(response => {
// recebemos a resposta e logamos o status
console.log(response.status)
// retorna o corpo em formato JSON
// requisição:
// tenta fazer um GET em URI inexistente
fetch('https://api.github.com/nonexistent-uri')
.then(response => {
if (response.ok) {
// não deve entrar aqui
console.log('success')
} else {
console.log(response.status)
}
const player = {
name: 'Cloud',
sayName () {
// Que valor 'this' tem aqui?
// Temos que olhar o momento que a função é chamada.
console.log(this.name)
}
}
// Dentro da função 'sayName' o 'this' é o que está antes do ponto.
// Constante no objeto 'window'
window.playerName = 'Tidus'
const sayGlobalName = function () {
console.log(this.playerName)
}
// A chamada abaixo não se enquadra a nenhuma das outras regras,
// portanto o 'this' na função é o objeto global
// ('window' no navegador ou 'global' no Node.js)
const player = {
name: 'Cloud'
}
const enemy = {
name: 'Sephirot'
}
// Função declarada global.
// Se chamar direto, o 'this' seria 'global' ou 'window'.
const player = {
name: 'Cloud',
hp: 100,
mp: 0,
printStatus () {
console.log(`${this.name} tem ${this.hp} de HP e ${this.mp} de MP.`)
}
}
// Função usa 'this', mas vamos setá-lo no momento da chamada.
// As linhas comentadas mostram o que o 'new' faz pra gente
const Player = function (name) {
// const this = {}
this.name = name
this.hp = 1000
this.mp = 0
// return this
}
// Função chamada com 'new', portanto o 'this' será