function foo(title) { console.log(title) } foo('title') foo('dust') foo('hello')
运行结果:
let user = { name: null, setUsername: function (name) { this.name = name }, getUsername: function () { return this.name }, } user.setUsername('dust') console.log(user.getUsername())
运行结果:
简写的形式:
let user = { name: null, setUsername(name) { this.name = name }, getUsername() { return this.name }, }
let foo = function () { console.log('hello') }
show() function show() { console.log('show') }
运行结果:
function sum(...args) { return args.reduce((a, b) => { return a + b }) } console.log(sum(1, 2, 3, 4, 5))
运行结果:
function sum(a, b, c) { //这里是形参 console.log(c) return a + b } console.log(sum(1, 2)) //这里是实参
运行结果:
function sum2(a, b = 1) { return a + b } console.log(sum2(1))
运行结果:
let i = 0 setInterval(() => { console.log(++i) }, 1000)
功能:每秒输出+1的数
运行结果:
function getSum(...args) { console.log(arguments) return args.reduce((a, b) => a + b) } console.log(getSum(1, 2, 3, 4, 5))
运行结果:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <button id="bt">hello</button> </body> <script> document.getElementById('bt').addEventListener('click', function () { alert(this.innerHTML) }) </script> </html>