函数为什么是JavaScript中的第一公民,以及函数在Ja
第一公民的概念?
一等公民这个说法,是谁提出来的呢?
根据维基百科,是由英国计算机科学家:克里斯托弗·斯特拉奇(Christopher Strachey)于1960年提出的这个概念。
在《计算机程序的结构和解释》这本书中有提到一等公民,说
1.它们可以用变量命名
2.它们可以作为参数传递给过程
3.它们可能作为程序的结果返回
4.它们可能包含在数据结构中
为什么是函数在JavaScript中是第一公民?
参考文章,阮一峰老师的文章 Javascript诞生记
JavaScript的作者,布兰登·艾奇(Brendan Eich)
他只用 10 天时间就把JavaScript设计出来了。
他借鉴了其他语言的一些优点:
借鉴C语言的基本语法
借鉴Java的数据类型和内存管理
借鉴Scheme语言,将函数提升到"第一等公民"(first class)的地位
借鉴Self语言,使用基于原型(prototype)的继承机制。
Javascript语言实际上是两种语言风格的混合产物
(简化的)函数式编程+(简化的)面向对象编程。
作为第一公民,有哪些特权?
在JavaScript中,函数拥有许多特权和优势,包括但不限于以下特点:
1.存储在变量中,也就是赋值给变量
var a = function () {
console.log('a')
}
2.作为参数传递,函数可以作为参数,传给另一个函数
function b(fn) {
fn()
}
b(a)
3.从函数中返回
function c() {
return function () {
console.log('c')
}
}
4.存储在数据结构中,譬如:作为对象的属性
var obj = {
d: function () {
console.log('d')
}
}
函数在JavaScript和Vue开发中使用场景
利用函数特性,在JavaScript和Vue开发中,有以下常用的场景:
1.代码重用和模块化:
function sum(arr) {
return arr.reduce((prev, cur) => prev + cur, 0);
}
const list = [1, 2, 3, 4, 5];
console.log(sum(list));
2.动态渲染
<template>
<div class="wrapper">
{{ message }}
<input type="text" v-model="text" />
</div>
</template>
<script>
export default {
name: "HaloWord",
data() {
return {
message: "Hello Vue!",
text: "",
};
},
// 通过watch监听数据变化,实现数据的动态渲染
watch: {
text: {
handler(newVal, oldVal) {
console.log(newVal, oldVal);
this.message = `Hello ${newVal}!`;
},
},
},
};
</script>
3.表单验证
<template>
<div class="wrapper">
<div>
<input v-model="email" @input="validateEmail" />
<span>{{ validationMessage }}</span>
</div>
</div>
</template>
<script>
export default {
name: "TestFormComponent",
components: {},
props: {},
data() {
return {
email: "",
validationMessage: "",
};
},
watch: {},
computed: {},
methods: {
validateEmail() {
// 邮箱验证
let reg = /^.+@.+$/;
if (!reg.test(this.email)) {
this.validationMessage = "Invalid email";
} else {
this.validationMessage = "";
}
},
},
created() {},
mounted() {},
};
</script>
<style scoped>
.wrapper {
}
</style>
4.异步操作和回调处理
function fetchData(callback) {
setTimeout(() => {
const data = { id: 1, name: 'Data' };
callback(data);
}, 1000);
}
fetchData(data => {
console.log(data); // { id: 1, name: 'Data' }
});
5.动态路由配置和权限控制
const routes = [
{ path: '/', component: Home },
{ path: '/admin', component: Admin, meta: { requiresAdmin: true } }
];
router.beforeEach((to, from, next) => {
if (to.meta.requiresAdmin && !userIsAdmin()) {
next('/'); // 如果不是管理员,重定向到首页
} else {
next();
}
});
6.动态样式和主题切换
<template>
<div :class="themeClass">
...
</div>
</template>
<script>
export default {
data() {
return {
darkTheme: true
};
},
computed: {
themeClass() {
return this.darkTheme ? 'dark-theme' : 'light-theme';
}
}
}
</script>
7.懒加载
const routes = [
{
path: '/halo',
component: () => import('../components/HaloWord.vue'),
},
{
path: '/test',
// 懒加载
component: () => import('../components/Test.vue'),
}
];
8.国际化
const messages = {
en: { welcome: 'Welcome' },
fr: { welcome: 'Bienvenue' }
};
function getLocalizedString(key, locale) {
return messages[locale][key] || key;
}
console.log(getLocalizedString('welcome', 'en')); // 输出 "Welcome"
最后的话
以上,如果对你有用的话,不妨点赞收藏关注一下,谢谢 🙏
😊 微信公众号: OrzR3
💖 不定期更新一些技术类,生活类,读书类的文章。
查看18道真题和解析