JavaScript 函数有 4 种调用方式。
每种方式的不同方式在于 this 的初始化。
1.作为一个函数调用
function myFunction(a, b) {
return a* b;
}
myFunction(10, 2); // myFunction(10, 2) 返回 20
或
function myFunction() {
return this;
}
myFunction(); // 返回 window对象
(this为window对象)
2.作为方法调用
var myObject = {
firstName:"John",
lastName: "Doe",
fullName: function () {
return this.firstName + " " + this.lastName;
}
}
myObject.fullName(); // 返回 "John Doe"
(this为myObject对象)
3.使用构造函数调用函数
如果函数调用前使用了 new 关键字, 则是调用了构造函数。
// 构造函数:
function myFunction(arg1, arg2) {
this.firstName = arg1;
this.lastName = arg2;
}
// This creates a new object
var x = newmyFunction("John","Doe");
x.firstName; // 返回"John"
(this在构造函数中没有任何值)
4.作为函数方法调用函数
在JavaScript 中, 函数是对象。JavaScript 函数有它的属性和方法。
call() 和 apply() 是预定义的函数方法。 两个方法可用于调用函数,两个方法的第一个参数必须是对象本身。
两者的区别在于第二个参数:apply传入的是一个参数数组,call传入的是单一参数。
function myFunction(a, b) {
return a* b;
}
myObject = myFunction.call(myObject, 10, 2); // 返回 20
function myFunction(a, b) {
return a* b;
}
myArray = [10, 2];
myObject = myFunction.apply(myObject,myArray); // 返回 20
在 JavaScript严格模式(strict mode)下, 在调用函数时第一个参数会成为 this 的值, 即使该参数不是一个对象。
在JavaScript 非严格模式(non-strict mode)下, 如果第一个参数的值是 null 或 undefined, 它将使用全局对象替代。
(this为调用它的对象本身,myObject调用myFunction函数)