【问题标题】:Private functions similar to Java using Literals使用 Literals 的类似于 Java 的私有函数
【发布时间】:2014-08-25 22:03:14
【问题描述】:

我有一个如下的对象设置:

var StartScreenLayer = cc.Layer.extend({
ctor: function () {
    this._super();
    // this function can call createBackground!
    this.createBackground();
},
callCreateBackgroundToo: function () {
   // I can call createBackground too!
   this.createBackground();
},
createBackground: function () {
});

如何安排它以使 createBackground 是私有的,但其他其他对象不能调用类似 screenLayer.createBackground() 的东西并在对象上抛出 createBackground is undefined 类型错误?

【问题讨论】:

  • 看看JavaScript private methods。您可能想使用createBackground.call(this) 来回答一些问题。
  • 嘿,我看了看,看起来你必须跳过一堆圈才能让它工作。我刚刚决定使用现有的约定,即在函数前加上下划线。
  • 下划线前缀确实也是一个很好且易于使用的解决方案。仅供参考其他解决方案may not be that hard(但可能无法访问)
  • 哦,哇,我喜欢你的例子 2!将其添加为答案,我明天会接受。

标签: javascript html cocos2d-x cocos2d-js


【解决方案1】:

显然惯例是在它前面加上一个下划线。但这只是一个约定,因此您仍然可以调用“私有”函数。

我正在使用的 cocos2d 库就是这样做的,所以我想我也会这样做。

编辑:

按照 Volune 的建议,我采用了以下方法:

var StartScreenLayer = cc.Layer.extend(function() {
  function callCreateBackgroundToo() {
     // I can call createBackground too!
     createBackground(this);
  }
  function createBackground() {
  }
  return {
    ctor: function () {
        this._super();
        // this function can call createBackground!
        createBackground.call(this);
    }
  }
}());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 2012-08-26
    • 1970-01-01
    • 1970-01-01
    • 2011-08-03
    • 2017-04-03
    • 1970-01-01
    相关资源
    最近更新 更多