菁英数字科技(猩码)-猩码学苑-专注软件开发人才菁英教育
标题:
前端-王卓凡-20230531
[打印本页]
作者:
王卓凡
时间:
2023-6-13 18:15
标题:
前端-王卓凡-20230531
函数的创建方式
// 函数是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)
}());
欢迎光临 菁英数字科技(猩码)-猩码学苑-专注软件开发人才菁英教育 (http://www.xingmaxueyuan.com/)
Powered by Discuz! X3.4