聚合物中的私有非静态变量? [英] Private non-static variables in polymer?
问题描述
如何在聚合物中使用私有非静态变量?
How is it possible to have private non-static variables in polymer?
在:
<polymer-element name="component-one">
<script>
Polymer('component-one', {
internalState = 1,
ready() {
this.anotherInternalState = 1;
}
/* more variables and functions */
});
</script>
</polymer-element>
internalState和anotherInernalState都暴露在外面(例如可通过以下方式访问:
both internalState and anotherInernalState are exposed to outside (e.g. accessible through something like:
document.querySelector('component-one').internalState
(从外部更改internalState时可能不合需要使组件不稳定。)
(Which might be undesirable when changing internalState from outside makes the component unstable.)
其中:
<polymer-element name="component-two">
<script>
(function() {
var internalState = 1;
Polymer('component-two', {
/* some variables and functions */
});
})();
</script>
</polymer-element>
internalState从外部隐藏,但它是静态的,并在组件的所有实例中共享。
internalState is hidden from outside but it is static and shared across all the instances of the component.
有没有办法在聚合物对象中有一个私有的非静态变量?
Is there a way to have a private non-static variable inside polymer object?
推荐答案
这是一个纯粹的JavaScript问题,而不是Polymer问题。从ES5开始,JavaScript中没有私有实例成员,尽管ES6带来了一些新工具。
This is more of a pure JavaScript question than a Polymer question. As of ES5 there are no 'private instance members' in JavaScript, although ES6 brings some new tools.
我的建议是使用旧的预设私有实例变量的约定下划线( _internalState
)。
My suggestion is to use the old convention of prepending private instance variables with underscore (_internalState
).
否则,你必须对地图和闭包感到棘手。
Otherwise, you have to get tricky with maps and closures.
这篇关于聚合物中的私有非静态变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!