0

I've an object looks like this:

var obj ={

  property : '',
  myfunction1 : function(parameter){
     //do stuff here
  }
}

I need to set some private properties and functions, which can not be accessed/seen from outside of the object. It is not working with var property:, or var myFunction1

Next question is, if I call a function within or outside the object, I always have to do this with obj.myfunction(). I would like to asign "this" to a variable. Like self : this. and call inside the object my functions and variables with self.property and self.myfunction.

How? :)

0

3 Answers 3

1

There are many ways to do this. In short: If dou define a function inside another function, your inner function will be private, as long as you will not provide any reference to if.

(function obj(){
    var privateMethod = function() {};
    var publicMethod = function() {
        privateMethod();
        ...
    };

    return {
        pubMethod: publicMethod
    }
}());
Sign up to request clarification or add additional context in comments.

1 Comment

0
var obj = (function() {
  var privateProperty;
  var privateFunction = function(value) {
    if (value === void 0) {
      return privateProperty;
    } else {
      privateProperty = value;
    }
  };
  var publicMethod = function(value) {
    return privateFunction(value);
  }

  return {
    getPrivateProperty: function() {
      return privateFunction();
    },
    setPrivateProperty: function(value) {
      privateFunction(value);
    }
  }
})();

obj.setPrivateProperty(3);
console.log(obj.getPrivateProperty());
// => 3
console.log(obj.privateProperty);
// => undefined
obj.privateFunction();
// => TypeError: undefined is not a function 

Comments

0

Use closures. JavaScript has function scope, so you have to use a function.

var obj = function () {
    var privateVariable = "test";
    function privateFunction() {
        return privateVariable;
    }

    return {
        publicFunction: function() { return privateFunction(); }
    };
}();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.