javascript通过继承实现私有(private)变量

标签 javascript inheritance private-members

我在使用 javascript 时遇到了问题...
我想在一个类中声明一个私有(private)变量,该变量不能从其子类中使用...我尝试过的是:

function Person(){
    var _name
    this.setName = function(name){
        _name = name
    }
    this.getName = function(){
        return _name
    }
}

function GreetingPerson(){
    var self = this;
    self.sayHello = function(){
        console.log(self.getName() + ': "Hello!"');
    }
}

GreetingPerson.prototype = new Person()
GreetingPerson.prototype.contructor = GreetingPerson;

var manuel = new GreetingPerson()
manuel.setName('Manuel');
manuel.sayHello();

var world = new GreetingPerson()
world.setName('World');
world.sayHello();
manuel.sayHello();
console.log(manuel.name)

这样,name变量是私有(private)的,但它也是静态的,所以最后两个sayHello方法调用,会写成相同的输出。
我也尝试过以这种方式更改 Person 类:

function Person(){
    this.setName = function(name){
        this.name = name
    }
    this.getName = function(){
        return this.name
    }
}

但这样它就不再是私有(private)的了。
实现它的正确方法是什么?

最佳答案

编辑:使用像@teddybeard所说的东西,你也可以获得它:

function Person(){
    var _name;
    this.setName = function(name){
        _name = name;
    };
    this.getName = function(){
        return _name;
    };
  return this;
}

function GreetingPerson(){
    Person.call(this);
    this.sayHello = function(){
        console.log(this.getName() + ': "Hello!"');
    };
  return this;
}

GreetingPerson.prototype = new Person();
GreetingPerson.prototype.constructor = GreetingPerson;

var manuel = new GreetingPerson();
manuel.setName('Manuel');
manuel.sayHello();

var world = new GreetingPerson();
world.setName('World');
world.sayHello();
manuel.sayHello();
console.log(manuel._name);

但我不太确定这是否真的可以。问题是,如果您不在 GreetingPerson 的构造函数中执行类似 Person.call(this); 的操作,您将不会创建 的新实例Person 并且它将始终使用相同的 _name 值。

关于javascript通过继承实现私有(private)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13343054/

相关文章:

javascript - RxJS 每 x 秒从数组发出值,使用该值调用函数,如果失败则重试

c++ - 为什么允许内联函数操作私有(private)成员变量?

JavaScript 确认在某些操作系统上陷入无限循环的模糊/焦点事件

javascript - 将 'custom' 组件改编为 redux-forms?

javascript - 图像失去 CamanJS 对操作 Canvas 的影响

vb.net - 私有(private)变量实例化: When Defined or Within Constructor?

javascript - 使用 .call/.apply 隐藏类方法

c# - 控件和页面中的相同属性

css - 防止子元素使用父类

c++ - 对 OnResetDevice() 和 OnLostDevice() 的一般调用