2011年最后一篇博客——javascript工厂模式小例

2011最后一篇博客拉,一年没搞什么东西,酱油了大半年,以前晟丰软件老板圈钱跑了,都上新浪游戏和qq游戏首页了,还好及时跳槽了,不然这个年都不知道怎么过了,下半年在新单位一直没有找到好的定位,也没在团队发挥什么作用了,公司的几个项目也只是在其一搞了个聊天系统,其余时间都在酱油,研究了1年的node.js发现越研究越深奥,web服务器,linux,数据库等等,还好在年底有个node.js框架rrestjs产出,希望明年2012能有所建树吧,也希望cnodejs越办越好、node.js能在2012有所突破。

年底蛋疼看了下javascript秘密花园,感觉像后花园似的,其中一段挺有道理的,贴上:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
javascipt的new function(),在某些情况下会有所不同,我们看下面的例子:

function test(){
this.value = 1;
return this.value;
}
test.prototype = {
getter:function(){alert(this.value)}
}
var x = new test();
var y = test();


x.getter();//1
y.getter();//TypeError: y.getter is not a function

以上是正常的情况,new test()以后可以实例化test这个类,x的getter方法是执行x的原型链prototype上的方法。一切正常,但是当test返回值为非原子类型的时候,比如:数组,对象和function时,同样的代码x是无法将其原型链指向test.prototype。

我们看代码

1
2
3
4
5
6
7
8
9
10
11
12
function test(){
this.value = 1;
return [];// return {}, 或者return function(){} 都是如此
}
test.prototype = {
getter:function(){alert(this.value)}
}
var x = new test();
var y = test();

x.getter();//TypeError: x.getter is not a function
y.getter();//TypeError: y.getter is not a function

最后介绍一下javascript秘密花园里的工厂模式:个人觉得就是单例模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 function test(){
var value = 1;
return {
getter:function(){alert(value)}
};
}
var x = new test();
var y = test();

x.getter();//1
y.getter();//1
所以在new 一个类时要注意,return 返回值不能为非原子类型的值,当然我们也经常这样使用:
function test(){
if(!(this instanceof test)) return new test();
this.value = 1;
}
test.prototype = {
getter:function(){alert(this.value)}
}
var x = test();

x.getter();//1

这样就避免使用了new关键字,同时也可以将x的原型链指向test.prototype上了。