原型上定义的函数如何访问私有变量? [英] How can functions defined on the prototype access private variables?

查看:45
本文介绍了原型上定义的函数如何访问私有变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

原型方法如何在不暴露公共 getter 和 setter 的情况下访问构造函数中的私有变量(通过闭包访问的值).

How can a prototype method access private variables (values accessed via closures) in the constructor without exposing public getters and setters.

function User() {

     var value = 1;

     this.increment = function () {
         value++;
     };

     this.set = function (val) {
         value=val; 
    };
    this.get = function () {
         return value;
    };     
}

User.protptype.add = function (value) {
    this.set(this.get()+value);
}

如何去掉 get() 和 set() 并且仍然只有一个 add() 副本?

How can I get rid of get() and set() and still have only one copy of add()?

目的是确保 add() 函数只有一个实例,而不是为每个对象创建一个实例,而该对象能够访问私有变量,在这种情况下是构造函数中的值变量.

The intent is to ensure that there is only one instance of the add() function and not one created for each object while that object being able to access the private variables in this case the value variable in the constructor.

推荐答案

因为私有的概念从来不是 JavaScript 的一部分,因此没有办法自然地这样做.您只是在 JS 中模拟"私有.

Because the concept of private was never part of JavaScript thus there is no way to do so naturally. You are just "emulating" privates in JS.

唯一可以做到的方法是将方法声明放在构造函数的范围内,以便它可以看到私有"成员.但这意味着在每个实例上复制函数,并且函数存在于实例中,而不是原型中.

The only way you can do it is to place the method declaration inside the constructor's scope so that it can see the "private" members. But this would mean duplicating the function on every instance, and the function lives on the instance, not on the prototype.

function User(){

  var value = 1;

  this.add = function(newValue){
    value += newValue;
  };

}

这篇关于原型上定义的函数如何访问私有变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆