模块中的 Object.create 和私有函数
这是 ES5 的 Object.create 的独立实现:
window.createObject = (function() {
var F = function () {};
return function(o) {
F.prototype = o;
return new F();
}
}());
及其使用示例:
var cat = createObject(animal);
我注意到当尝试调用私有函数时,animal
的内部变得有点混乱,例如:
animal = (function() {
function privFunc(arg) {
this.property;
}
function publFunc(arg) {
privFunc.call(this, arg);
}
return {
publFunc: publFunc
}
}());
是否有遵循这种模式的更清晰的方法?特别是,不再需要 privFunc.call(this, arg)
。
另一种同样丑陋的方式是:
function privFunc(animal, arg) {
animal.property;
}
function publFunc(arg) {
privFunc(this, arg);
}
This is a standalone implementation of ES5's Object.create:
window.createObject = (function() {
var F = function () {};
return function(o) {
F.prototype = o;
return new F();
}
}());
and an example of its use:
var cat = createObject(animal);
I've noticed the internals of animal
are getting a little messy when trying to call private functions, e.g.:
animal = (function() {
function privFunc(arg) {
this.property;
}
function publFunc(arg) {
privFunc.call(this, arg);
}
return {
publFunc: publFunc
}
}());
Is there a cleaner way to follow this type of pattern? In particular, removing the need for privFunc.call(this, arg)
.
Another way, equally as ugly is:
function privFunc(animal, arg) {
animal.property;
}
function publFunc(arg) {
privFunc(this, arg);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不幸的是,这是结合 Object.create 和私有函数的唯一方法。创建的新对象只能访问定义原型的模块已公开的公共方法。在模块中使用私有方法需要将您想要使用的对象传递给这些方法 - 作为命名参数,或操作
this
的值Unfortunately this is the only way to combine Object.create and private functions. The new object created only has access to the public methods that the module which defines the prototype has exposed. Using private methods within the module requires passing to those methods the object which you'd like to work with - as either a named parameter, or manipulating the value of
this