I want to create a dependent property on my javascript object. I have an object like in the code snippet. I want to update isPawn property; when isNew property changes.
Is there a way for do something similar that automatically;
if(isNew){
isPawn = true;
}
But they are not have to be same. isNew can be 'false', when isPawn is 'true'
My Object:
var Soldier = function (id,name) {
this.id = id;
this.name = name;
this.isPawn = false;
this.isNew = false;
}
Yes, you can do this using a setter, here is an example:
class Soldier { #isNew = false; constructor(id,name) { this.id = id; this.name = name; this.isPawn = false; } set isNew(val) { this.#isNew = val; this.isPawn = val; } get isNew() { return this.#isNew; } } const soldier = new Soldier(); soldier.isNew = true; console.log('isNew:', soldier.isNew, 'isPawn', soldier.isPawn); soldier.isNew = false; console.log('isNew:', soldier.isNew, 'isPawn', soldier.isPawn); soldier.isPawn = true; console.log('isNew:', soldier.isNew, 'isPawn', soldier.isPawn);
#isNew
is a private field in this case I'm using it to keep track of what the value of isNew
should be (what the getter should return).
Here is an example using a function instead of a class:
var Soldier = function(id, name) { this.id = id; this.name = name; this.isPawn = false; this.isNewPriv = false; Object.defineProperty(this, 'isNew', { set: function(val) { this.isNewPriv = val; this.isPawn = val; }, get: function() { return this.isNewPriv } }); } var soldier = new Soldier(1, 'none'); soldier.isNew = true; console.log("isNew:", soldier.isNew, "isPawn:", soldier.isPawn); soldier.isNew = false; console.log("isNew:", soldier.isNew, "isPawn:", soldier.isPawn); soldier.isPawn = true; console.log("isNew:", soldier.isNew, "isPawn:", soldier.isPawn);
Make a class and instantiate as needed
class Soldier { constructor(id, name, isNew) { this.id = id; this.name = name; this.isPawn = isNew? true: {something: "whaterverElse"}; this.isNew = isNew; } DoSomething(){ this.isNew = false; } } var soldier = new Soldier(1, 'Tim', true); console.log(soldier); function somethingElseHappened(){ soldier.DoSomething(); } somethingElseHappened(); console.log(soldier);
you can make a default values for this properties like this:
var Soldier = function (id,name,isPawn = false,isNew = false) {
this.id = id;
this.name = name;
this.isPawn = isPawn;
this.isNew = isNew;
}
and if you want to change there values to any object for you just do like this:
var newSolider = new Solider(1,"foo",false,true);
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.