2011年最后一篇博客——javascript工厂模式小例
by snoopyxdy
at 2012-01-21 11:33:38
original http://snoopyxdy.blog.163.com/blog/static/601174402012021105440833
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
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
所以在new 一个类时要注意,return 返回值不能为非原子类型的值,当然我们也经常这样使用:function test(){
var value = 1;
return {getter:function(){alert(value)}
};
}
var x = new test();
var y = test();
x.getter();//1
y.getter();//1
这样就避免使用了new关键字,同时也可以将x的原型链指向test.prototype上了。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