this的四种调用模式:方法调用模式,函数调用模式,构造器调用模式、apply调用模式

1、方法调用模式

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

myObject.increment(2);
console.log(myObject.value) // 3

this指向的是这个对象

2、函数调用模式

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();
}
myObject.double();
console.log(myObject.value); // 6

helper里的this不指向myObject,指向全局对象,所以需要通过that=this,指向当前myObject。

3、构造器调用模式

var Quo = function (string) {
	this.status = string;
}

Quo.prototype.get_status = function () {
	return this.status;
}

var myQuo = new Quo("confused");
console.log(myQuo.get_status); // confused

4、apply调用模式

var statusObject = {
	status: 'OK'
}
var status = Quo.prototype.get_status.apply(statusObject); // OK
05-22 16:06