场景1 – 一切正常:
var AwesomeObject = function() { var self = this; self.whatstuff = 'really awesome'; } AwesomeObject.prototype.doStuff = function() { var self = this; console.log('i did '+self.whatstuff+' stuff'); return self; } var awesome = new AwesomeObject(); //returns a new AwesomeObject awesome.doStuff(); // prints 'i did really awesome stuff' on the console
现在我甚至想要它甚至是美妙的:
var AwesomeObject = function() { var f = function() { console.log('i am awesome'); } var self = f; self.whatstuff = 'really awesome'; return self; } AwesomeObject.prototype.doStuff = function() { var self = this; console.log('i did '+self.whatstuff+' stuff'); return self; } var awesome = new AwesomeObject(); //returns the interal f object awesome(); // prints 'i am awesome' awesome.doStuff(); // throws an error
新的AwesomeObject本身应该返回一个可执行函数,这样我就可以说’awesome();’
但我希望它继承AwesomeObject.prototype.
添加self.prototype = AwesomeObject.prototype;没有帮助.
var AwesomeObject = function() { var f = function() { console.log('i am awesome'); } var self = f; self.whatstuff = 'really awesome'; self.prototype = AwesomeObject.prototype; return self; }
好吧,我可以将AwesomeObject.prototype函数 – 一个接一个地 – 复制到f的范围内
var AwesomeObject = function() { var f = function() { console.log('i am awesome'); } var self = f; self.whatstuff = 'really awesome'; self.doStuff = function() { AwesomeObject.prototype.doStuff.apply(self,arguments); } return self; }
但我认为必须有更好的方式,更好的模式,它是什么?
这个问题让我发疯,帮助真的很感激.
一般来说:如何创建一个函数对象
>可以用new创建
>返回可以执行的函数对象
>继承给定原型的所有属性和方法
?
有办法吗?
谢谢
弗朗茨
解决方法
一个非常简单的模式是工厂.
var AwesomeObject = (function() { var AwesomeObject = function() { this.whatstuff = 'really awesome'; }; AwesomeObject.prototype.doStuff = function() { console.log('i did ' + this.whatstuff + ' stuff'); return this; }; return function() { var o = new AwesomeObject(); var f = function() { console.log("I am awesome"); }; for (var k in o) { f[k] = o[k]; } return f; }; })(); var foo = AwesomeObject(); foo(); foo.doStuff();
我们的想法是将您的功能和对象分成两部分.您的对象存在于函数的本地范围内,该函数可以使用该对象.
对象本身完全通过原型继承.
这是最干净的解决方案.