Posted on 2012-09-09 01:28
BZ 阅读(320)
评论(0) 编辑 收藏
JavaScript Constructor就是那些希望被使用"new Xxx()"的函数。例如:
function Point(x, y) {
this.x = x;
this.y = y;
}
调用时,
var p = new Point(1, 2);
p.x // => 1
p.y // => 2
Constructor的初始化过程,可以用如下过程来模拟:
1). 创建一个空对象,也就是 {};
2). 设置该对象的constructor属性;
3). 调用constuctor函数,并将constuctor中的this设置为步骤1)中创建的对象。
var p = {}; //创建空对象
p.constructor = Point; //关联构造方法
Point.call(p, 1, 2); //函数调用,使用Point.apply亦可