简体   繁体   中英

Private and public methods in RequireJS objects

I'm not certain how to set methods private or public when using requirejs, as it uses shorthand for object declaration. In the following code, I would prefer if the property "id" and the method "prepareId" were private.

define(['jquery'], function ($) {
    var Asset = Class.extend({
        init: function() {
            this.id = "12345";
        }
        ,getAsset: function() {
          return this.prepareId(this.id);
        }
        ,prepareId: function(id) {
          return "#" + id;
        }
    });
    return Asset;
});

I think you are slightly confused. require.js does not impose rules on what you return. If you want to return a constructor that creates "private" attributes and functions you can do so.

So the following (if I understand correctly what you mean by private) should work just fine.

define(['jquery'], function ($) {
  var Asset = function () {
    var id;
    function prepareId(id) {
      ...
    };
    ...
  };
  return Asset;

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM