javascript - javascript中的私有(private)变量意味着

标签 javascript function scope closures private

JavaScript 中的“私有(private)变量”是什么意思? javascript 中没有声明“私有(private)变量”。

所以我们通常使用“_”或闭包。

在这一点上,我很好奇“关闭”。 我从另一个网站得到了例子。

function createAnimal(name, job) {
  // "Private" variables here
  let _name = name;
  let _job = job;

  // Public variables here
  return {
    // Getter Methods
    getName() {
      return _name;
    },
    getJob() {
      return _job;
    },
    // Setter Methods
    setName(newName) {
      _name = newName;
    },
    setJob(newJob) {
      _job = newJob;
    }
  };
}

上面的例子
我们可以更改 setName 的 _name '私有(private)变量'。

真实
“私有(private)变量”意味着我们不能访问变量?还是常量?

最佳答案

希望这对你有帮助:

Private members are made by the constructor. Ordinary vars and parameters of the constructor become the private members.

function Container(param) {
    this.member = param;
    var secret = 3;
    var that = this;
}

This constructor makes three private instance variables: param, secret, and that. They are attached to the object, but they are not accessible to the outside, nor are they accessible to the object's own public methods. They are accessible to private methods. Private methods are inner functions of the constructor.

function Container(param) {

    function dec() {
        if (secret > 0) {
            secret -= 1;
            return true;
        } else {
            return false;
        }
    }

    this.member = param;
    var secret = 3;
    var that = this;
}

The private method dec examines the secret instance variable. If it is greater than zero, it decrements secret and returns true. Otherwise it returns false. It can be used to make this object limited to three uses.

By convention, we make a private that variable. This is used to make the object available to the private methods. This is a workaround for an error in the ECMAScript Language Specification which causes this to be set incorrectly for inner functions.

Private methods cannot be called by public methods. To make private methods useful, we need to introduce a privileged method.

引用:Read more

关于javascript - javascript中的私有(private)变量意味着,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59150578/

相关文章:

javascript onclick 不工作?

c++ - 我的递归函数没有返回正确的值

function - 检查函数的参数是否为函数

jquery - AJAX-响应数据未保存到全局范围?

javascript - window.on 加载函数只在一个页面上执行

javascript - 与 jquery 连接

javascript - D3 实时饼图不更新?

c - 在 C 函数中修改数组

javascript - Controller 内的 Angular $http 函数作用域

javascript - 将方法应用于数组的其他方法