js中的this

this的四種調用模式:方法調用模式,函數調用模式,構造器調用模式、apply調用模式javascript

一、方法調用模式java

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

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

this指向的是這個對象app

二、函數調用模式函數

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。this

三、構造器調用模式prototype

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

四、apply調用模式code

var statusObject = {
	status: 'OK'
}
var status = Quo.prototype.get_status.apply(statusObject); // OK
相關文章
相關標籤/搜索