function

What is a function?

  • The package body of N statements to achieve features and functions
  • Only functions can be executed; other types of data cannot be executed

Why use a function?

  • Improved code reuse
  • Easy to read

How do you define a function?

  • Function declaration
function fn() {
    console.log('fn()')}Copy the code
  • expression
var fn = function () {
    console.log('fn()')}Copy the code

How is a function called (executed)?

  • Test () : call directly
  • Obj.test () : called by object
  • New test() : new call
  • Test.call /apply(obj) : temporarily call test as a method of OBj
var obj = ()
function test() {
    this.xxx = 'test'
}
test.call(obj) // obj.test (), which allows a function to be called as a method specifying any object
console.log(obj.xxx)
Copy the code

The callback function

What is a callback function?

  • The custom
  • No manual call required
  • Eventually perform

Common callback functions?

  • Dom event callback function
  • Timer callback function
    • Timeout timer
    • Cycle timer
  • Ajax request callback function
  • Lifecycle callback function
// dom event callback function
document.getElementById('btn').onclick = function () {
    alert(this.innerHtml)
}
Copy the code
// Timer callback function
setTimeout(function () { / / timeout
    alert('hello')},2000)
//
setInterval(function() { // Interval loop
    console.log('hello')},100)
Copy the code