I am creating a hasOwnProperty
method for my (class) object in JavaScript.
What this does is: I feed it an object like this:
{
"key": "value",
"anotherKey": false
}
and it should loop through this and create based on the keys in the object above properties in my (class) object. However this is not possible, because the variable I pass as property, is literally the variable, instead of the value it stores.
Example:
let x = "foo";
this.x = "bar"; //x is the property, instead of the value assigned to x.
What I have tried so far:
class foob {
//other methods etc
constructor(externalObj) {
this._startValues = externalObj;
this.hasOwnProperty({"aKeyINeedToBeCertainHasBeenSet": "a default value if the key >aKeyINeedToBeCertainHasBeenSet< has not been set"});
}
hasOwnProperty(dynamicObject) {
let $this = this;
let property;
Object.keys(dynamicObject).forEach(function(dynamicObjectKey, index) {
//variable property should now be: _aKeyINeedToBeCertainHasBeenSet ->
//how do I use the value the variable "property" stores as the property name
//of my object, rather then having JS use the variable "property" as property name?
property = `_${dynamicObjectKey}`;
if ($this._startValues.hasOwnProperty(`${dynamicObjectKey}`)) {
//value of the variable property should be the "property name"!
$this.property = $this._startValues[dynamicObjectKey];
} else {
//value of the variable property should be the "property name"!
$this.property = dynamicObject[dynamicObjectKey]
}
});
}
}
//aKeyINeedToBeCertainHasBeenSet is not set, and therefore a default value should be provided to this property.
new foob({
"key": "value",
"anotherKey": false
});
Is there any way to achieve this? I have to use hasOwnProperty
too much right now, which is cluttering my code.