Change js object property getter/setter [duplicate] - javascript

This question already has answers here:
How to "override" a defined (get-)property on a prototype?
(4 answers)
Closed 2 years ago.
Is it possible to change the value of the property getter of an object?
let's say we have
const autoIncrementer = (function() {
let value = 0;
return {
incr() {
value++
},
get value() {
return value
}
};
})();
function anotherFunctin (){//log smth.}
autoIncrementer.value = anotherFunction;
P.S. I know that this does not do any good, so I just need an explanation of why is this so? and is there any way to achieve this goal?

You can use setter along with getter.
let obj = {
get propName() {
// getter, the code executed on getting obj.propName
},
set propName(value) {
// setter, the code executed on setting obj.propName = value
}
};
About getters/setters usage - read more here

Related

Why inside a foreach loop you can not use global variables in Typescript? [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 3 years ago.
I have a property with a simple foreach loop, inside this loop I want to use a global variable but I receive a error.
When I
Create an internal variable of the property that receives the global value to be able to use it within the loop
simpleArray = [0,1,2];
simpleArray2 = [0,1,2];
get resume() {
let localArray = this.simpleArray;
this.simpleArray2.forEach(function (element, index) {
console.log(localArray); // [0,1,2]
console.log(this.simpleArray); // return error undefined
});
return 'something';
}
Use arrow function instead :
this.simpleArray2.forEach((element, index) => {
console.log(localArray);
console.log(this.simpleArray);
});

How to use a method in another method (ES6 class) [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 5 years ago.
When I use the work method in the doTasks method, I get the error "Uncaught TypeError: Cannot read property 'work' of undefined". I don't exactly understand what is going on.
class Employee {
constructor(name) {
this.name = name;
this.totalWorktime = 0;
}
work(worktime) {
this.totalWorktime += worktime;
}
doTasks(tasks){
tasks.forEach(function(element) {
this.work(element);
});
}
}
doTasks(tasks) {
tasks.forEach((element) => {
this.work(element);
});
}
remove the "function" so this is really "this"
You are in a different closure.
Either use arrow notation (recommended)...
doTask(tasks) {
tasks.forEach((element) => {
this.work(element);
});
}
...or create a reference to the class instance outside the loop.
doTasks(tasks) {
let that = this;
tasks.forEach(function(element) {
that.work(element);
});
}

Why are methods like setters used, instead of changing properties directly in Javascript? [duplicate]

This question already has answers here:
Why use getters and setters/accessors?
(37 answers)
Closed 7 years ago.
With an object defined.
var bob = {age: 10};
Defined setter as:
bob.setAge = function (newAge){
bob.age = newAge;
};
So we can change a property as:
bob.setAge(20)
Instead of simply:
bob.age = 20;
or
bob["age"] = 20;
Is best practices the reason?
Because this allows to hide and save the state of the object against unwanted side effects
bob.setAge = function (newAge){
bob.age = newAge || 0; // age must never be undefined or null;
};
You have to wrap everything in a module/closure/function to actually hide the fields which carry the object's state.
var user = (function () {
var name = '';
function getName() {
return name;
}
function setName(value) {
if (!value) {
console.warn('setName: empty value passed');
}
name = value || '';
}
return {
getName: getName,
setName: setName
};
}());
// undefined, the variable could not be resolved
console.info(user['name']);
user.setName('Sergio Prada');
console.info(user.getName());
// warning
user.setName(null);
// empty string, undefined or null will never be returned
console.info(user.getName());
For getters, it allows for validation checks to be applied to make sure that only correct values will ever be set.
As well as this, you can encapsulate the internal method of storage for the variable. For example, you might encrypt the data if you're storing it in the database, but decrypt in the getter so it's automatically ready

Change value object Javascript [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 8 years ago.
I have a normal object in javascript, contenting functions and values.
This is my example object:
var MyObject = {
myData: 1,
a: function() {},
b: function() {}
}
Now in the function a there is some logic that fire on it, but it should change even the value of myData property.
But when i try get it from the method b, that value come as an undefined value, instead of the value changed.
I created a JsFiddle with a small example of the behaviour of the my object. I realized that it how Javascript behave, but I didn't understand why.
The issue is because this within the click handlers refers to the element which was clicked, not the object the handler functions are members of. You need to cache this:
a: function () {
var self = this;
$('.setValue').click(function() {
self.myData = 2;
});
},
b: function () {
var self = this;
$('.getValue').click(function() {
alert(self.myData);
});
}
Updated fiddle
In JavaScript, each function has its own this argument. In your case, you want to access the outer function's this variable so you should do something like this:
var that = this;
Here is the updated jsfiddle:
http://jsfiddle.net/xaaLQ/5/

JS/Jquery variable schange event [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
detect variable change in javascript
How can i found out that my variable has changed?
I have an event that performed every time when my variable is for example == 1, i want it to perfome only when my variable changes.
You can do that via a property setter, which is a newly-standardized part of the language (new as of the ECMAScript5 specification). That will only work for a property defined with a setter on an object, not with any old variable or property.
Here's an example of an object with a foo property with both a getter and a setter:
var obj = {};
Object.defineProperty(obj, "foo", (function(){
var value = 42;
function fooGet() {
display("Getting: " + value);
return value;
}
function fooSet(newValue) {
display("Setting: " + newValue);
value = newValue;
}
return {
get: fooGet,
set: fooSet
};
})());
Live example, but only works on browsers with support for ECMAScript5 properties, which I think is just Google Chrome at the moment
Or of course, just directly use getter and setter functions rather than properties. :-)
Simple: Don't use a primitive variable but an object which has a "setter" method to change the value. In the setter, you can call additional code.
You can't do this with primitives. The only way it would be possible is if you encapsulated the variable in an object, and added some custom events to this object.
#T.J. I think #Aaron is suggesting an object that does something like this:
var myVar = new Watched(1, function (newValue) { alert(newValue) });
myVar.add(2); // alert(3);
myVar.add(10); // alert(13)
Where Watched maintains an internal value that is updated by methods, which fire a callback to say they have updated.
EDITED:
Ok maybe not what #Aaron was thinking:)
I had something very simple like this in mind:
function Watched (initVal, cb) {
var value = initVal;
function add (val) {
value += val;
cb(value);
}
// return public methods
return { add: add };
}
You could use the setInterval method to periodically check the variable's value and do your stuff if it's what you want.
It's not a nice solution, though. The other suggestions are better.
http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/
EDIT:
var myVar = 0;
var intervalId = setInterval('checkVariable(myVar);', 3000);
function checkVariable(theVar) {
if (theVar == 1) {
alert('Variable is 1.');
}
}
That will execute checkVariable(myVar) every 3 seconds.

Categories

Resources