ecma6 prevent access to whole instance [duplicate] - javascript

This question already has answers here:
Private properties in JavaScript ES6 classes
(41 answers)
Closed 7 years ago.
Hi I have the following class definition:
'use strict'
class Human {
constructor(name, age) {
this._name = name || null;
this.age = age || 'no age defined';
this.rights = ['Human Rights'];
}
get this() {
return 'access denied';
}
set name(name) {
this._name = this._name ? this._name : name;
}
get name() {
return this._name;
}
}
let me = new Human();
console.log(me); // this should return a string "access denied"
I thought it might be possible to define a getter for the whole instance. But this is not, or?
Does anyone know anything about that? Or is there an alternative methods to create restricted Classes?
kind regards
martin

No, but what you could do is put some code in a module and only export part of it.
// human.js
class SecretHuman {
constructor(name) {
this.name = name;
}
}
let human = new SecretHuman('Bob');
export class Human {
secret() {
console.log(`Secret human is ${human.name}`);
}
}
// test.js
import {Human} from './human';
new Human().secret();

Related

Why do i keep getting undefined when accessing a inherited property? [duplicate]

This question already has an answer here:
Javascript call Parent constructor in the Child (prototypical inheritance) - How it works?
(1 answer)
Closed 9 months ago.
I'm trying to use prototypal inheritance and its not working, everytime i try i keep getting undefined:
function HospitalEmployee(name) {
this._name = name;
this._remaningVacationDays = 20;
}
function Nurse() {}
Nurse.prototype = Object.create(HospitalEmployee.prototype)
const nurseOlynyk = new Nurse("Olynyk", ["Trauma", "Genetics"])
console.log(nurseOlynyk._remainingVacationDays) //Prints undefined
What am i doing wrong?
I need use Class and Extends for it same as :
class HospitalEmployee {
constructor(name){
this._name = name;
this._remaningVacationDays = 20;
}
}
class Nurse extends HospitalEmployee {
constructor(name, otherParams){
super(name);
this.otherParams = otherParams;
}
}
const nurseOlynyk = new Nurse("Olynyk", ["Trauma", "Genetics"])
console.log(nurseOlynyk)

"this" in JavaScript classes why it's throwing this error? [duplicate]

This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
How does the "this" keyword in Javascript act within an object literal? [duplicate]
(4 answers)
Closed 1 year ago.
when it comes to this in javascript classes it suppose to refer to the class instances but at
somechildmethod() method it don't it throws an error saying TypeError: Cannot read property 'name' of undefined and I know this error will go away if I use the arrow function but I want to know why please!
class parent {
constructor(name, score) {
this.name = name;
this.score = score;
}
someparentmethod() {
console.log("Hi!");
}
}
class child extends parent {
constructor(name, score, thirdprop) {
super(name, score);
this.thirdprop = thirdprop;
}
somechildmethod() {
return function () {
console.log(this.name);
};
}
}
const child1 = new child("zahal", 1);
const child2 = child1.somechildmethod();
child2();

Angular - Property does not exist on type [duplicate]

This question already has answers here:
Ignore Typescript Errors "property does not exist on value of type"
(10 answers)
Closed 2 years ago.
I am new to Angular. I took the following example from a book, to get familiar with javascript classes. I try to load it using main.ts . However, I get the following error: error TS2551: Property '_weather' does not exist on type 'MyClass'. Did you mean 'weather'? Can anybody explain me why? It should work, it is a copy/paste from a book. I can make it work if I manually add _weather: string; and name: string; declarations. But it shouldn't be necessary.
class MyClass {
constructor(name, weather) {
this.name = name;
this._weather = weather;
}
set weather(value) {
this._weather = value;
}
get weather() {
return `Today is ${this._weather}`;
}
printMessages() {
console.log("Hello " + this.name + ". ");
console.log(this.weather);
}
}
let myData = new MyClass("Adam", "sunny");
myData.printMessages();
Error is self explained.
error TS2551: Property '_weather' does not exist on type 'MyClass'. Did you mean 'weather'?
In your code snippet you are trying to assign value to the property that don't exists.
this._weather is arranged to be private since you create setter/getter to it.
In typescript you should name private variables with underscore in order to avoid duplicates
class MyClass {
private _weather: any;
private _name: any;
constructor(name: any, weather: any) {
this.name = name;
this.weather = weather;
}
set name(value) {
this._name = value;
}
get name() {
return `Name is ${this._name}`;
}
set weather(value) {
this._weather = value;
}
get weather() {
return `Today is ${this._weather}`;
}
printMessages() {
console.log("Hello " + this.name + ". ");
console.log(this.weather);
}
}
let myData = new MyClass("Adam", "sunny");
myData.printMessages();
If you don't want to specify setters/getters then write constructor like so
In this case Typescript will automatically generate thore properties.
class MyClass {
constructor(private name: any, private weather: any) {}
printMessages() {
console.log("Hello " + this.name + ". ");
console.log(this.weather);
}
}
let myData = new MyClass("Adam", "sunny");
myData.printMessages();
class MyClass {
private name: string;
private _weather: string;
constructor(name, weather) {
this.name = name;
this._weather = weather;
}
set weather(value) {
this._weather = value;
}
get weather() {
return `Today is ${this._weather}`;
}
printMessages() {
console.log("Hello " + this.name + ". ");
console.log(this._weather);
}
}
let myData = new MyClass("Adam", "sunny");
myData.printMessages();
Hiya, if I'm understanding this correct. You did not have the properties defined in the class. I have added them as private properties expecting the type "string".
Also, I updated the printMessages() method to return _weather as opposed to weather in your example.
I haven't tested this, but I wish you luck in your project.

JS class getter setters [duplicate]

This question already has answers here:
JSON stringify ES6 class property with getter/setter
(7 answers)
Closed 4 years ago.
According to Martin, this syntax can be used to define a class in nodeJS:
class Person {
constructor() {
this.id = 'id_1';
}
set name(name) {
this._name = name;
}
get name() {
return this._name;
}
usage:
myPerson.name = "Saul"; // save the value in `_name` variable.
Slight problem with this convention is that calling JSON.stringify(myPerson) will print the following:
{
"_name": "Saul"
}
But if I remove the underline from the setter function, and write it as the following:
set name(name) {
this.name = name;
}
the setter function will recursively call itself forever. So is there no way of using this nice getter-setter syntax, and still use the name property? I'm running nodejs.
I dont see a problem at all here. If you deserialize it, it works as expected:
const saul = Object.assign(new Person, JSON.parse('{"_name": "Saul"}'));
console.log(saul.name);

Use prototypical inheritance with ES6 [duplicate]

This question already has answers here:
ES6 - declare a prototype method on a class with an import statement
(3 answers)
Closed 5 years ago.
How can we use the class keyword in ES6 to add methods on the fly like we did in ES5?
https://jsfiddle.net/user1212/7c57eou3/
class Person{
constructor(name){
this.name = name;
}
getName(){
return this.name;
}
setName(name){
this.name = name;
}
}
function Company(cName){
this.cName = cName;
}
Company.prototype.getName = function(){
return this.cName;
}
How can Person have a new method added after the class has been defined?
You don't use the class keyword to add further methods. Just like in ES5, you simply assign them to the prototype object:
class Person { … }
…
Object.assign(Person.prototype, { // Object.assign provides a neater syntax
logName() { // but really is the same as Person.prototype.logName = …
console.log(this.name);
},
alertName() {
alert(this.name);
}
});
As others have answered your specific question, you'd use prototype
But just as a reminder, if you are modifying prototype of a class to add methods, maybe you want to use extends syntax and create a "subclass", so you always use the same class logic without touching prototype.
For most programmers that come from other languages is difficult to understand prototype-style classes, so if you could use ES6 only typical class style, I would say go for it. Like this:
class Hello {
constructor(name) {
this.name = name;
}
hello() {
return 'Hello ' + this.name + '!';
}
static sayHelloAll() {
return 'Hello everyone!';
}
}
class HelloWorld extends Hello {
constructor() {
super('World');
}
echo() {
alert(super.hello());
}
}
var hw = new HelloWorld();
hw.echo();
alert(Hello.sayHelloAll());
taken from here

Categories