文章目录
一、JavaScript函数定义
1.1 函数声明
function myFunction(a, b) {
return a * b;
}
1.2 函数表达式
var x = function (a, b) {return a * b};
var z = x(4, 3);
1.3 函数构造器
函数也可以通过名为 Function() 的内建 JavaScript 函数构造器来定义。
var myFunction = new Function("a", "b", "return a * b");
var x = myFunction(4, 3);
//您实际上无需使用函数构造器。上面的例子这么写也是一样的:
var myFunction = function (a, b) {return a * b};
var x = myFunction(4, 3);
1.4 自调用函数
自调用函数就是自己调用自己的函数,只要在函数体外边加()声明自己是一个函数再加上再函数体后面加( )就可以实现自调用
(function () {
var x = "Hello!!"; // 我会调用我自己
})();
上面的函数实际上是一个匿名的自调用函数
1.5 箭头函数
箭头函数没有自己的this、因此不适合定义对象方法
// ES6
const x = (x, y) => x * y;
//如果函数是单个语句,则只能省略 return 关键字和大括号。因此,保留它们可能是一个好习惯:
//实例
const x = (x, y) => { return x * y };
二、JavaScript函数参数
- JavaScript函数不会对参数值进行任何检查,当传的值为空时会给它默认0值
- arguments对象包含函数调用时使用的参数数组
x = sumAll(1, 123, 500, 115, 44, 88);
function sumAll() {
var i, sum = 0;
for (i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum;
}
三、call( )、apply( )
3.1 call( )方法
你可以用任意的对象来访问其他对象的方法、
var person = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
var person1 = {
firstName:"Bill",
lastName: "Gates",
}
var person2 = {
firstName:"Steve",
lastName: "Jobs",
}
person.fullName.call(person2); // 将返回 "Steve Jobs"
这里的fullName是person的方法,person2想要访问不属于它的方法那么这时就要借助person.fullName.call(person2);
回调函数还可以带有参数
var person = {
fullName: function(city, country) {
return this.firstName + " " + this.lastName + "," + city + "," + country;
}
}
var person1 = {
firstName:"Bill",
lastName: "Gates"
}
person.fullName.call(person1, "Seattle", "USA");
3.2 apply( )方法
apply( )方法和call( )方法类似,唯一不同的是apply( )方法接收的参数可以是 数组
var person = {
fullName: function(city, country) {
return this.firstName + " " + this.lastName + "," + city + "," + country;
}
}
var person1 = {
firstName:"Bill",
lastName: "Gates"
}
person.fullName.apply(person1, ["Oslo", "Norway"]);
apply( )方法还可以找到数字中的最大值
Math.max.apply(null, [1,2,3]); // 也会返回 3
四、JavaScript闭包
五、JavaScript Static方法
static 类方法是在类本身上定义的。
您不能在对象上调用 static 方法,只能在对象类上调用。
class Car {
constructor(name) {
this.name = name;
}
static hello() {
return "Hello!!";
}
}
let myCar = new Car("Ford");
// 您可以在 Car 类上调用 'hello()' :
document.getElementById("demo").innerHTML = Car.hello();
// 但不能在 Car 对象上调用:
// document.getElementById("demo").innerHTML = myCar.hello();
// 此举将引发错误。