创建模块化模式对象的继承 [英] Creating inheritance on revealing modular pattern objects
问题描述
我正在尝试在对象之间创建某种继承:
I'm trying to create some kind of inheritance between objects:
var foo = (function(){
function doFooStuff(){
console.log(arguments.callee.name);
}
return {
doFooStuff: doFooStuff
}
})();
var bar = (function(){
$.extend(this, foo);
function doBarStuff(){
console.log(arguments.callee.name);
doFooStuff();
}
return {
doBarStuff: doBarStuff,
}
})();
bar.doBarStuff();
bar.doFooStuff(); //<-- Uncaught TypeError:
//Object #<Object> has no method 'doFooStuff'
为什么不是 doFooStuff
可以在这里访问?你会推荐另一种方法,而不是使用 $ .extend
?
Why isn't doFooStuff
accessible here? Would you recommend another approach than using $.extend
?
推荐答案
$.extend(this, foo);
this
不是你从下面的函数返回的对象(实际上它不能是因为它是在这次调用之后创建的),而是全局对象 - 检查 MDN对这个
关键字的介绍。
this
is not the object which you return from the function below (in fact it cannot be since it's created after this call), but the global object - check MDN's introduction to the this
keyword.
对于你想做的事,有两种方法:
For what you want to do, there are two ways:
-
将所有属性从
foo
复制到bar
对象创建后:
Copy all properties from
foo
onto yourbar
object after it is created:
var bar = (function() {
…
return {…};
})();
$.extend(bar, foo);
您也可以直接在返回的对象上执行此操作:
You can do that as well directly on the returned object:
return $.extend({…}, foo);
此模式的变体允许您覆盖 foo
属性。将 foo
复制到一个空对象中,然后将 bar
属性写入其中:
A variant of this pattern allows you to overwrite foo
properties. Copy foo
into an empty object, then write your bar
properties to it:
return $.extend({}, foo, {…});
使用原型继承。 创建一个继承其属性的对象从 foo
,然后将 bar
属性写入其中:
Use prototypical inheritance. Create an object that inherits its properties from foo
, and then write your bar
properties to it:
return $.extend(Object.create(foo), {…});
现在当 foo
之后发生变化时,你仍然可以在 bar
上访问这些新属性(除非它们被自己的属性遮蔽)。请注意,旧版环境可能不支持 Object.create
,但您可以轻松地将其填充。
Now when foo
changes afterward, you still can access those new properties on bar
(unless they're shadowed by own properties). Notice that Object.create
might not be supported in legacy environments, but you can easily shim it.
如@ raina77ow所述,您的 doBarStuff
函数也存在缺陷。 doFooStuff
函数不在您的函数范围内,您无法更改它。您永远无法从 foo
模块访问私有声明的函数和变量,只能访问那些公开的函数和变量 - 如果确实需要它们,请考虑使用不同的模式或应用程序设计。但是, doFooStuff
是导出的(公共) foo
对象的属性,从该对象继承(无论哪个属性)以上说明的方法)。因此,您也可以通过使用 this.doFooStuff()
来访问它作为 bar
的方法。
As noted by @raina77ow, your doBarStuff
function is flawed too. The doFooStuff
function is not in the scope of your function, and you cannot change that. You never will be able to access the private declared functions and variables from the foo
module, only those that are public - if you did need them, consider a different pattern or app design. However, doFooStuff
is a property on the exported (public) foo
object, from which bar inherits (regardless in which of the above demonstrated ways). Therefore, you can access it as a method of bar
as well, usually by using this.doFooStuff()
.
这篇关于创建模块化模式对象的继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!