日期:2014-05-16  浏览次数:20311 次

Js中的4中调用模式

参数this在面向对象编程时非常重要,它的值取决于调用的模式,在JavaScript中有四种调用模式:方法调用模式、函数调用模式、构造器调用模式、apply调用模式。

1、方法调用模式 The Method Invocation Pattern

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

?2、函数调用模式 The Function Invocation Pattern

// 当函数调用此模式时,this被绑定到全局变量。在helper方法中获取不到this.
myObject.double = function() {
	var that = this;
	var helper = function() {
		that.value = add(that.value, that.value);
	};
	helper();
}
myObject.double();
alert(myObject.value);

?3、构造器模式 The Contructor Invocation Pattern

// javaScript是一种基于原型继承的语言。对象可以直接从其他对象继承属性。
// 如果在一个函数面前带上new来调用,那么将创建一个隐藏连接到该函数的peototype的成员的新对象,同时this将会绑定到那个新对象上
// 创建一个名为Quo的的构造函数,它构造一个带有status属性的对象
var Quo = function(string) {
	this.status = string
}
// 给Quo的所有实例提供一个名为getStatus的公共方法
Quo.prototype.getStatus = function() {
	return this.status;
}

var v = new Quo('IVY');
alert(v.getStatus())

?

4、Apply调用模式 The Apply Invocation Pattern

// apply方法接收两个参数,第一个将被绑定给this的值,第二个就是一个参数数组
var array = [4, 5];
var sum = add.apply(null, array);
alert(sum);
var statusObject = {
	status : 'A-OK'
}
var status = Quo.prototype.getStatus.apply(statusObject);
alert(status)

??

?

?

?

?

?

?

?