apply

    虽然在一个独立的函数调用中,根据是否是strict模式, this 指向 undefined window ,不过,我们还是可以控制 this 的指向的!

    要指定函数的 this 指向哪个对象,可以用函数本身的 apply 方法,它接收两个参数,第一个参数就是需要绑定的 this 变量,第二个参数是 Array ,表示函数本身的参数。

    apply 修复 getAge() 调用:

    function getAge() {

    var y = new Date().getFullYear();

    return y - this.birth;

    }



    var xiaoming = {

    name: '小明',

    birth: 1990,

    age: getAge

    };



    xiaoming.age(); // 25

    getAge.apply(xiaoming, []); // 25, this指向xiaoming, 参数为空

    另一个与 apply() 类似的方法是 call() ,唯一区别是:

    • apply() 把参数打包成 Array 再传入;

    • call() 把参数按顺序传入。

    比如调用 Math.max(3, 5, 4) ,分别用 apply() call() 实现如下:

    Math.max.apply(null, [3, 5, 4]); // 5

    Math.max.call(null, 3, 5, 4); // 5

    对普通函数调用,我们通常把 this 绑定为 null