JS中函数调用的四种方式

一 以函数形式调用

function fun(){
    alert("hello world");
}
fun();

调用时this指针指向的是函数所属的对象,当函数没有被自身的对象调用时,this就是全局变量,在WEB浏览器中This指向浏览器对象(window对象)

二 函数作为对象方法调用

var myObject = {
    firstName:"John",
    lastName: "Doe",
    fullName: function () {
        return this.firstName + " " + this.lastName;
    }
}
myObject.fullName();         // 返回 "John Doe"

This指向函数所属对象本身,也就是myObject

三 使用构造函数调用函数

使用new关键字调用函数,即是构造函数

// 构造函数:
function myFunction(arg1, arg2) {
    this.firstName = arg1;
    this.lastName  = arg2;
}

// This creates a new object
var x = new myFunction("John","Doe");
x.firstName;                             // 返回 "John"

构造函数的调用会创建一个新的对象,新对象会继承构造函数的属性和方法。

构造函数中 this 关键字没有任何的值。
this 的值在函数调用时实例化对象(new object)时创建。也就是指向了新创建的那个对象

四 使用apply()和call()方法调用

call()方法

function myFunction(a, b) {
    return a * b;
}
myFunction.call(myObject, 10, 2);      // 返回 20

可以看到call方法调用时,第一个参数必须是一个对象,这样调用的用处即是这里的This指向了函数第一个参数所给的对象

/*定义一个Person类*/ 
function Person(name,age) { 
     this.name=name; 
     this.age=age;
} 
 /*定义一个学生类*/ 
 function Student(name,age,grade) { 
    //Person.apply(this,arguments);//特点:this指代student对象,只接收2个参数,arguments为隐式类数组对象,用来接收传入的参数;
      Person.call(this,name,age);//特点:this指代student对象,可以接收任意多个参数
      this.grade=grade; 
 } 
 var student =new Student("zhangsan",22,"二年级");//方法Student()也是object的一个实例
 //测试 
 alert("name:"+student.name+"\n"+"age:"+student.age+"\n"+"grade:"+student.grade);
//学生类里面我没有给name和age属性赋值啊,为什么又存在这两个属性的值呢,这个就是apply的神奇之处.

apply()

function myFunction(a, b) {
    return a * b;
}
myArray = [10,2];
myFunction.apply(myObject, myArray);   // 返回 20

call()方法和apply()方法的区别即是,apply方法调用函数时,相关实参依次放在第一个参数之后,而apply()传递的是一个数组

posted @ 2020-08-13 15:13  二仙桥下摸鱼  阅读(4774)  评论(1编辑  收藏  举报