我在使用 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/