I would like to start that I'm not feeling comfortable with JS.
I've experienced a problem with implementing private methods in prototype. Let's say we have a Person class. I want to expose greet method but keep getName private.
function Person(name) {
this.name = name;
}
Person.prototype = (function() {
function getName() {
return this.name;
}
function greet() {
console.log("hello " + getName());
}
return {
greet: greet
}
})();
p = new Person('Szymon');
p.greet();
above code won't work as getName doesn't have context ("this" points to window where name doesn't exist).
My solution to this problem was:
function greet() {
console.log("hello " + getName.call(this));
}
however it's get a little bit messy with bigger class.
Is this a clean solution? I would be grateful for any feedback.
The way you've written it getName
is not a method, but a static function. If you don't want to make it a public method (I don't see a good reason why a getter would be private), and don't want to use .call()
, then you will need to pass the instance explicitly:
Person.prototype = (function() {
function getName(self) {
return self.name;
}
function greet() {
console.log("hello " + getName(this));
}
return {
constructor: Person,
greet: greet
}
})();
I'd consider all three solutions equally clean.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.