函数包含一组语句,它们是JS的基础模块单元,用于代码复用、信息隐藏和组合调用。
函数调用方式:
匿名函数立即执行
具名调用
表达式调用
事件调用
< type=\"text/ \">
/*具名函数调用 如果是使用function关键字进行的函数定义,
那么定义会自动提前
*/
f1();
function f1(){
alert(\"调用f1函数\");
}
/*表达式的形式 */
var f2 = function(){
alert(\"调用f2函数\");
}
f2();
/*匿名函数的立即执行*/
(function(n){
alert(\"调用函数\"+n);
})(10);
/*事件触发回调函数执行*/
window. = function(){
alert(\"windows加载完成\");
}
</ >
构造函数:
当任意一个普通函数用于创建一类对象时,它就被称作构造函数或构造器。
< type=\"text/ \">
/*构造函数的命名 驼峰命名*/
function createPerson(username,age){
this.username = username;
this.age = age;
this.sayHello = function(){
alert(\"hello world\");
}
}
let person = new createPerson(\"lisi\",26);
console.log(person);
</ >
函数上下文:
this 是JS语言的一个关键字,它代表函数运行时,自动生成的一个内部对象,只能在函数内部使用。
纯粹的函数调用,指全局对象
作为构造函数调用,指创建出来的对象
作为apply调用时
事件回调函数中,指触发事件的对象
< type=\"text/ \">
var username = \'李四\';
function person(){
console.log(this);
}
person(); //Window
function person2(){
console.log(this.username);
}
person2(); //李四
</ >
<!DOCTYPE html>
<html>
<head>
< charset=\"utf-8\">
< ></ >
</head>
<body>
<button id=\"btn\">提交</button>
</body>
< type=\"text/ \">
function createPerson(username,age){
this.username = username;
this.age = age;
this.sayHellow = function(){
alert(\"helloworld\");
}
}
function createStudent(username,age,sex){
createPerson.apply(this,[username,age]);
this.sex = sex;
}
var student = new createStudent(\"张三\",20,\"男\")
console.log(student); //createStudent age: 20 sayHellow: ƒ ()sex: \"男\"username: \"张三\"__proto__:
var btn = document.getElementById(\"btn\");
btn. = function(){
console.log(this); //<button id=\"btn\">提交</button>
}
</ >
</html>
继续阅读与本文标签相同的文章
-
吉利缤越,液晶仪表盘,运动座椅,L2级别自动驾驶,8秒破百
2026-05-18栏目: 教程
-
苏泊尔破壁机:技术革新 家族合力
2026-05-18栏目: 教程
-
OpenStack Train版本今日正式发布并开放下载
2026-05-18栏目: 教程
-
文在寅:八年后将韩国打造成全球第一个自动驾驶国家
2026-05-18栏目: 教程
-
Android Studio运行Hello World程序
2026-05-18栏目: 教程
