【发布时间】:2013-09-19 23:10:20
【问题描述】:
我正在尝试在对象之间创建某种继承:
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 以外的其他方法吗?
【问题讨论】:
-
当你做
$.extend(this, foo);你想做什么?this代表全局对象(在浏览器中通常是window)。您的意思是像使用new function(){的构造函数一样调用第二个 IIFE 吗? -
How to implement inheritance in JS Revealing prototype pattern? 的可能重复项(尽管这仅适用于原型继承模式)
-
@BenjaminGruenbaum 哦,我以为它指的是
bar。不,我不想创建一个新实例,我只想要“静态”对象。 -
@Johan 请参阅@Bergi 的答案,以获取有关
this工作原理的更详细说明的链接。
标签: javascript jquery