简体   繁体   English

javascript对象中的私有方法

[英]private method in an javascript object

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 它不适用于var property:,var myFunction1

Next question is, if I call a function within or outside the object, I always have to do this with obj.myfunction() . 下一个问题是,如果我在对象内部或外部调用函数,则始终必须使用obj.myfunction()进行此obj.myfunction() I would like to asign "this" to a variable. 我想将“ this”赋给一个变量。 Like self : this . 喜欢self : this and call inside the object my functions and variables with self.property and self.myfunction . 并在对象内部用self.propertyself.myfunction调用我的函数和变量。

How? 怎么样? :) :)

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. 简而言之:如果dou在另一个函数中定义一个函数,则内部函数将是私有的,只要您不提供对if的任何引用即可。

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

    return {
        pubMethod: publicMethod
    }
}());
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 

Use closures. 使用闭包。 JavaScript has function scope , so you have to use a function. JavaScript具有函数作用域 ,因此您必须使用一个函数。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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