我遇到了使用javascript的问题...
我想在一个不能从子类中使用的类中声明一个私有变量......我试过的是:
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)
这样名称变量是私有的,但它也是 static ,所以最后一个wo sayHello 方法调用,会写相同的输出 我也试过用这种方式改变 Person 类:
function Person(){
this.setName = function(name){
this.name = name
}
this.getName = function(){
return this.name
}
}
但通过这种方式,它不再是私人的 实现它的正确方法是什么?
答案 0 :(得分:2)
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);
但我不确定这实际上是否正常。问题是,如果你在Person.call(this);
的构造函数中没有执行GreetingPerson
之类的操作,则不会创建Person
的新实例,并且它将始终使用相同的_name
价值。
答案 1 :(得分:1)
如果有时间,请查看Eloquent Javascript。我认为这段代码应该适用于您的继承目的。
function Person() {
var _name
this.setName = function(name) {
_name = name
}
this.getName = function() {
return _name
}
}
function GreetingPerson() {
Person.call(this);
this.sayHello = function() {
console.log(this.getName() + ': "Hello!"');
}
}
// taken from Eloquent Javascript
function clone(object) {
function OneShotConstructor() {}
OneShotConstructor.prototype = object;
return new OneShotConstructor();
}
GreetingPerson.prototype = clone(Person.prototype);
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);