我正在尝试使用这个模式创建一个“构造函数”:
function mything() {
var a, b, c;
...
return {
publicFunc: function() {
//access private vars here
}
};
}
//usage
mything1 = mything();
mything2 = mything();问题是,我还想让它通过instanceof测试:
assert(mything1 instanceof mything === true);有没有办法做到这一点?使用常规构造函数将不起作用,因为原型函数不能访问私有变量。
发布于 2013-03-29 07:07:28
您需要使用稍微不同的设计模式来拥有私有变量,并使其成为mything的一个实例
function mything() {
var a, b, c;
...
this.publicFunc = function() {
//access private vars here
}
};
}
//usage
var mything1 = new mything();
mything1.publicFunc();
var mything2 = new mything();发布于 2013-03-29 07:25:55
这在技术上是可行的,但您可以更优雅地解决您的问题(解释如下):
function mything() {
var a, b, c;
function PrivateConstructor() {
this.publicFunc = function() {}
}
// this is the magic that makes it happen:
PrivateConstructor.prototype = mything.prototype;
return new PrivateConstructor();
}
mything1 = mything();
assert(mything1 instanceof mything); // passes或者,使用EcmaScript 5功能:
function mything() {
var a, b, c;
var object = Object.create(mything.prototype);
object.publicFunc = function() {}
return object;
}
mything1 = mything();
assert(mything1 instanceof mything); // passes解释
如果右侧操作数是一个函数,并且存储在该函数的prototype属性中的对象包含在左侧操作数的原型链中,则instanceof运算符将生成true。
第一个示例重用mything.prototype作为另一个临时函数的“原型”属性,该临时函数仅用于生成一个对象(其原型链中包含mything.prototype )。第二个示例通过使用Object.create()直接从mything.prototype继承来创建这样一个对象。
这两个对象都继承自mything.prototype,因此将通过object instanceof mything测试。
也就是说,jfriend00提出的模式在提供您想要的功能的同时,开销更小,更容易阅读。
https://stackoverflow.com/questions/15693694
复制相似问题