我的账户
猩码学苑

专注C++开发菁英教育

亲爱的游客,欢迎!

已有账号,请

如尚未注册?

彭婉嘉-20230531

[复制链接]
鱼小仙 发表于 2023-6-14 18:49:28 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题
函数的创建方式
// 函数是JS中的一等公民
// 函数的创建方式
// 1.函数声明式 - 可以在任意位置调用函数 - 因为存在函数提升
fn()
function fn() {
  console.log('函数声明式')
}
fn()
// 2.函数表达式 - 只能在函数后面调用
// 如果使用var就会存在变量名的提升
// 如果使用let是不存在变量的提升
// fun()
let fun = function () {
  console.log('函数表达式')
}
fun()

// 3.构造函数方式 - 使用new关键字 - 不推荐使用
let f = new Function('console.log(123)')
f()
console.log(f instanceof Function) //true
console.log(f instanceof Object) //true
函数的应用场景和this的指向问题
// 1.全局中创建和使用函数 - this指向是window
function fn() {
  console.log('fn')
  console.log(this)
}
window.fn()

// 2.事件中的函数 - this指向了事件的触发者
const btn = document.querySelector('button')
btn.onclick = function () {
  console.log('btn')
  console.log(this)
}

// 3.定时器中的函数 - this指向了window
setInterval(function () {
  console.log('定时器')
  console.log(this)
}, 2000)

// 4.构造函数 - this指向了实例化对象
function Person(age) {
  this.age = age
}
Person.prototype.sayAge = function () {
  console.log(this.age)
}
const p1 = new Person(18)
p1.sayAge()
console.log(p1)

// 5.箭头函数 - this没有指向的。它的this就是父级的this
// 6.IIFE(立即执行函数)
; (function () {
  console.log(this)
})();

(function () {
  console.log(this)
}());

回复

使用道具 举报

关注0

粉丝0

帖子26

发布主题
大家都在学
课堂讨论
一周热帖排行最近7x24小时热帖
关注我们
专注C++菁英教育

客服电话:18009298968

客服时间:9:00-21:00

猩码学苑 - 专注C++开发菁英教育!( 陕ICP备2025058934号-1 )

版权所有 © 陕西菁英数字科技有限公司 2023-2026