How to prevent updating attribute directly in js/ts class? [duplicate] - javascript

This question already has answers here:
Why can I access TypeScript private members when I shouldn't be able to?
(10 answers)
Closed 2 years ago.
class Animal {
privateAttribute
setPrivateAttribute(value) {
this.privateAttribute = value
}
}
new Animal().setPrivateAttribute('good way') //ok
new Animal().privateAttribute = 'not allowed' // no
I want to prevent update privateAttribute directly, the only way to set privateAttribute is call setPrivateAttribute function. What shold I do?

Please put all the private variable inside your constructor.
class Animal {
constructor() {
let privateAttribute = 'default';
this.setPrivateAttribute = newValue => {
privateAttribute = newValue
}
this.getPrivateAttribute = () => privateAttribute;
}
}
let newAnimal = new Animal()
// get variable value
newAnimal.getPrivateAttribute()
// Set new Value
newAnimal.setPrivateAttribute('New Value')

Related

"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();

Create proxy with dynamic functions [duplicate]

This question already has answers here:
Add a return type of string when a function is accessed like a variable
(2 answers)
Harmony proxy, detect whether property was accessed or called
(2 answers)
Closed 3 years ago.
I want to change styles and get them, using this method:
style(element).color("red") // Change color to red
style(element).color // get current color
This is what I tried:
let styleProxy = {
get: (object, property) => {
return (value) => {
object[property] = value;
return new Proxy(object, styleProxy);
}
return object[property];
}
}
let style = (element) => {
return new Proxy(element.style, styleProxy);
}
let element = document.getElementsByClassName("test")[0];
let test = style(element)
.color;
I know, that these functions are created dynamically but how do I check if I'm calling this proxy function-based or property-based.

Class methods assigned to variable (alias) lose the value of this in Javascript [duplicate]

This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 3 years ago.
I am having a problem understanding why the following does not work. I looked at the other suggested answers and none of them addresses this clearly in the context of a new class object.
Given the code below:
class Example1 {
constructor(v1) {
this.v1 = v1;
}
method1() {
console.log("v1 value = ",this.v1)
}
}
const example1 = new Example1("value1");
const alias1 = example1.method1;
example1.method1();
alias1();
When I call alias1(), why is this undefined?
Its because the context of this changes when you call the alias1 (method1) just as a regular function instead of calling it on object.
When you call it on the object then the context of this is that object and in your case that context is lost and is either undefined or it falls back to the context of the global object (window in browsers) depending on the strict mode
You can set the context for this inside the alias using bind method to any object or you can define it inside some other object and that use that object to call it.
class Example1 {
constructor(v1) {
this.v1 = v1;
}
method1() {
console.log("v1 value = ", this.v1)
}
}
const example1 = new Example1("value1");
example1.method1();
const alias = example1.method1;
const alias1 = alias.bind(example1);
alias1();
const example2 = {v1: 'foo', alias}
example2.alias();
Because this refers to method1 which does not have a v1 ,
You can use bind in the constructor :
Bind creates a new function that will have this set to the first parameter passed to bind().
class Example1 {
constructor(v1) {
this.v1 = v1;
this.method1 = this.method1.bind(this);
}
method1() {
console.log("v1 value = ", this.v1)
}
}
const example1 = new Example1("value1");
const alias1 = example1.method1;
example1.method1();
alias1();

I can't use setter's in my javascript class because is not a function [duplicate]

This question already has answers here:
Getters \ setters for dummies
(14 answers)
Closed 3 years ago.
I try to use setter method with my class Test but my log return "TypeError: testObject.id is not a function"
class test {
constructor() {
this._id = 0;
}
get id(){
return this._id;
}
set id(newId){
this._id = newId;
}
}
const testObject = new test();
console.log(testObject.id); // return 0
testObject.id(12); //return TypeError: myTest.id is not a function
console.log(testObject.id);
I expect the ouput will be 12 but i obtain TypeError.
To use a setter, you do assignment, you don't write a function call:
testObject.id = 12;
Live Example (I've also changed the name to Test; the overwhelming convention in JavaScript is to capitalize constructor functions):
class Test {
constructor() {
this._id = 0;
}
get id(){
return this._id;
}
set id(newId){
this._id = newId;
}
}
const testObject = new Test();
console.log(testObject.id); // 0
testObject.id = 12;
console.log(testObject.id); // 12

Javascript define private variable [duplicate]

This question already has answers here:
Private properties in JavaScript ES6 classes
(41 answers)
Closed 5 years ago.
I want to build a class using javascript like in c, the main problem is private attribute.
var tree = {
private_var: 5,
getPrivate:function(){
return this.private_var;
}
};
console.log(tree.private_var);//5 this line want to return unaccessible
console.log(tree.getPrivate());//5
so I want to detect the access from tree.private_var and return unaccessible, and this.private_var return 5.
My question is: Is there any way to set private attribute in javascript?
EDIT: I saw this way
class Countdown {
constructor(counter, action) {
this._counter = counter;
this._action = action;
}
dec() {
if (this._counter < 1) return;
this._counter--;
if (this._counter === 0) {
this._action();
}
}
}
CountDown a;
a._counter is not accessible?
but
Define tree as a function instead of JavaScript object, define private variable in the function by var keyword, define public getting function by this. keyword and create a new instance by using the function
var Tree = function(){
var private_var = 5;
this.getPrivate = function(){
return private_var;
}
}
var test = new Tree();
test.private_var; //return undefined
test.getPrivate(); //return 5
In ES6, you can do this but it is not supported by IE so I wouldn't recommend
class Tree{
constructor(){
var private_var =5;
this.getPrivate = function(){ return private_var }
}
}
var test = new Tree();
test.private_var; //return undefined
test.getPrivate(); //return 5

Categories