Js的四种调用方式和this绑定对象——《JavaScript语言精粹》

JavaScript一共有四种调用模式:方法调用模式、函数调用模式、构造器调用模式和apply调用模式。

方法调用模式:

当一个函数被保存为对象的一个属性时,我们称之为一个方法。当一个方法被调用时,this被绑定到该对象。

var myObject = {
    value: 0,
    increment:function(inc){
        this.value += typeof inc === 'number' ? inc : 1;
    }
};
myObject.increment();
document.writeln(myObject.value);//1

myObject.increment(2);
document.writeln(myObject.value);//3

函数调用模式

当一个函数并非一个对象的属性时,那么它被当作一个函数来调用。此时this被绑定到全局对象。这是语言设计上到一个错误。如果语言设计正确,当内部函数被调用时,this应该仍然绑定到外部函数的this变量。这个bug导致方法不能利用内部函数来帮助它工作。解决的方法是:

var add = function(a,b){
    return a+b;
};
myObject.double = function(){
    var that = this;//解决方法

    var helper = function(){
        that.value = add(that.value, that.value);
    };

    helper();//内部函数调用时,this被绑定到全局对象
};

myObject.double();
document.writeln(myObject.value);

构造器调用模式

如果在一个函数前面带上new来调用,那么将创建一个隐藏连接到该函数的prototype成员到新对象,同时this将会被绑定到那个新对象上。

var Quo = function(string){//构造器函数
    this.status = string;
};
Quo.prototype.get_status = function(){
    return this.status;
}

var myQuo = new Quo("confused");
document.writeln(myQuo.get_status());//confused

apply调用模式

apply方法允许我们构建参数数组来调用函数,同时它也允许我们选择函数的this值。apply方法接收两个参数。第一个是将被绑定给this的值。第二个就是一个参数数组。

var array = [3,4];
var sum = add.apply(null,array);//7

var statusObject = {
    status:"A-OK"
};
var status = Quo.prototype.get_status.apply(statusObject);//"A-OK"

猜你喜欢

转载自blog.csdn.net/wsjtwmy/article/details/82534701