如何存储变量:特权方法,静态属性
How to store variables: Privileged method, static property
而不是直接说:
var thing = timeConsumingMethod();
我把变量隐藏在一个方法中,像这样:
function _thing() {
var thing = timeConsumingMethod() );
return thing;
}
它被调用了很多次。我担心我让事情变得非常低效。我假设每次我调用"_thing()"来获取变量时它都会调用timeConsumingMethod(这是不需要的,它总是一样的)。
如何以简单有效的方式管理这些类型的变量?像这样的东西是解决方案吗?:
function _thing() {
return _thing.thing
}
_thing.thing = timeConsumingMethod();
基本上,我想要一个函数的保护,并(理想情况下)访问我的变量使用_thing()或类似的东西,但我只希望timeConsumingMethod运行一次。
编辑:试过这个,也不工作:
function _thingy() {
var thing = timeConsumingMethod();
}
_thingy.test = function() {
return( _thingy.thing)
}
为什么不直接:
function SomethingTimeConsuming() { ... }
function LazyThing(sourceFunction) {
this.sourceFunction = sourceFunction;
this.value = null;
this.Value = function() {
if ( this.value == null) this.value = sourceFunction();
return this.value;
}
}
JSFiddle: http://jsfiddle.net/YSAjJ/
输出:[14:20:20.079] Calling time-consuming function *(1 time)
相关文章:
- electronic BrowserWindow的最小高度和宽度在hide()show()方法之后不起作用
- 有没有任何方法可以将控制器从文件加载到ui路由器$stateProvider中
- 数组在递归方法中设置为null
- 打破承诺链的好方法是什么
- 在使用Polymer'加载所有json文件后执行方法;s的核心ajax
- 使用“;这个“;JavaScript原型方法中的关键字
- 序列化数据属性中对象的最可靠方法
- 使用Objective-C的JavaScript注入方法
- 使构造函数参数具有ES6类方法的特权
- 有没有一种方法可以在构造对象后注入特权方法
- 无法通过javascript中的特权方法访问私有方法
- Javascript OOP-带有私有变量的非特权公共方法
- OOP Javascript-通过另一个公共方法从公共方法访问特权方法
- 为什么特权方法和公共方法有区别?如何知道使用哪个
- 如何存储变量:特权方法,静态属性
- 覆盖基类的特权方法
- 我如何使特权JS方法
- JavaScript可见性:私有和特权方法:
- 如何创建共享的,特权的,公共的方法
- 私有方法和特权方法的区别