方法调用模式
如果调用表达式包含一个提取属性的动作(即包含一个.点表达式或[subscript]下标表达式),那么它就是被当做一个方法来调用
方法可以使用this访问自己所属的对象,所以它能从对象中取值或对对象进行修改。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变量。这个设计错误的后果就是方法不能利用
内部函数来帮助他们工作, 因为内部函数的this被绑定了错误的值,所以不能共享该方法对对象的访问权。
幸运的是,有一个很容易的解决方案:如果该方法定义一个变量并给它赋值为this, 那么内部函数就可以通过那个变量访问到this。按照约定,我们把那个变量命名为that.
function add(a, b) {
return a + b;
}
myObject.double = function() {
var that = this;
var helper = function() {
that.value = add(that.value, that.value);
}
helper();
};
myObject.double();
document.writeln(myObject.value); // 6
构造器调用模式
如果在一个函数前面带上new来调用,那么背地里将会创建一个连接到该函数的prototype成员的新对象,同时this会被绑定到那个新对象上
var Quo = function(string) {
this.status = string;
};
Quo.prototype.get_status = function() {
return this.value;
}
var myQuo = new Quo("confused");
document.writeln(myQuo.get_status());
Apply调用模式
因为JavaScript是一门函数式的面向对象编程语言, 所以函数可以拥有方法apply 方法让我们构建一个参数数组传递给调用函数。它也允许我们选择this的值。
var array = [3, 4];
var sum = add.apply(null, array);
var statusObject = {
status: 'A-OK'
};
var status = Quo.prototype.get_status.apply(statusObject); // status的值为'A-OK'