What is the best-practice to validate and/or preprocess a property before assigning it to an object in JavaScript?
The application for that would be to create an object and to guarantee that a specific property of it will always have a specific type or maybe do some preprocessing with it.
For example, if I create an object:
var obj = {
settings: {}
};
Then when I do something like:
obj.settings = "{foo: bar}";
It would automatically check the type of the assignment - if it is a string, it will try to parse it to an object; if it's an object, it will just assign it; else it will throw an error. This would protect the object's property against being assigned to "anything".
Also, does this make sense at all to do in JavaScript or am I just trying to have strong typed features in a language that is weak typed?
You can do this with Object.defineProperty:
var obj = {}
Object.defineProperty(obj, 'settings', {
set: function (x) {
if (typeof x === 'string') {
this._settings = JSON.parse(x)
} else {
this._settings = x
}
},
get: function () {
return this._settings
}
})
obj.settings = {foo: 'bar'}
console.log(obj.settings)
obj.settings = '{foo: "baz"}'
console.log(obj.settings)
However, if this is desirable depends on your specific use case. I frankly never used it so far. My recommendation is: don't get fancy :)
IMHO this is not strong typing, but the opposite as you are more dynamic. If you want strong typing you could try flow or TypeScript
A simple solution could be to use a getter/setter like below that gets triggered if a value is assigned to a property and how to process it :
let obj = {}
Object.defineProperty(obj, "settings", {
set: function (value) { // preprocess
this._value = value;
},
get: function () {
return "changed";
}
});
You could do this afterward:
obj.settings = "{foo: bar}";
Let me know if this makes any sense.
Reference:
MDN Reference: Object.defineProperty()
Related
This is a purely theoretical question here (though one I think is an interesting thought exercise). I was just working on a JavaScript object (documentation-related) and the somewhat-unusual thought crosses my mind: is there a way to make a key/value pair entry within said object capable of reading its own key as part of its value? That is to say:
Assuming I have a JavaScript object used for the purposes of serializing data:
{
"someKey":()=>"M-me? MY key is '" + voodoo(this) + "'! Thanks so much for taking an interest!"
}
...is there a way I can get "M-me? MY key is 'someKey'! Thanks so much for taking an interest!" as an (albeit: rather asinine) output when addressing the key? I totally don't care what the structure would look like, nor what the type of the Value of the portion of the KVP would be, NOR what arguments would need passed it (if any? I'm just assuming it would have to be a function, after all).
I mean, of course it's possible; it's code. It's ALL possible (I've seen a quine that can ascertain its own SHA-512 hash, for heaven sake). But I find it to be an interesting thought experiment, and wanted to see if anyone already had some Code Kung Fu/Source Santeria (even at the abstract/pseudo-code level) and/or someone that might have some ideas.
I've tinkered with going so far as to actually parse the JavaScript source file line-by-line and test for the remainder of the output string to place it (worked, but lame... What if it's a constructed object?), then thought of stringifying it and RegEx-ing it out (worked, but still pretty weak... Relies too much on advance knowledge of what would have to be an unchanging structure).
I'm now fiddling with attempting to filter the object on and by itself to try and isolate the key making the request, which I expect will work (-ish), but still leaves me feeling kind of like the bull in a china shop. I can extend the Object prototype (I know, I know. Theoretical, remember?) so the self-reference doesn't pose a problem, but I'm stumped as to providing a means for the KVP to identify itself uniquely without having to search for some set portion of string.
Anyone have any thoughts? No holds barred: this will probably never see the light of a production environment - just an interesting puzzle - so feel free to muck with prototypes, include libraries, fail to indent... whatever*. Frankly, it doesn't really even have to be in JavaScript; that's just what I'M using. It's 2:30am here, and I'm just noodling on if it's DOABLE.
* (Please don't fail to indent. Twitch-twitch (ಥ∻.⊙) It seems I lied about that part.)
Reflexively lookup the key on call
This is probably the most surefire way to do it. When obj.foo() is called, then foo is executed with obj set as the value of this. This means that we can lookup the key from this. We can examine the object easily the hardest thing is to find which key contains the function we just executed. We can try to do string matching but it might fail for:
const obj = {
foo: function() { /* magic */ },
bar: function() { /* magic */ },
}
Because the contents of the functions will be the same but the keys are different, so it's not easy to differentiate between obj.foo() and obj.bar() by doing string matching.
However, there is a better option - naming the function:
const obj = {
foo: function lookUpMyOwnKey() { /* magic */ }
}
Normally, there is pretty much no effect whether you give the function a name or not. However, the thing that we can leverage is that the function can now refer to itself by the name. This gives us a fairly straightforward solution using Object.entries:
"use strict";
const fn = function lookUpMyOwnName() {
if (typeof this !== "object" || this === null) { //in case the context is removed
return "Sorry, I don't know";
}
const pair = Object.entries(this)
.find(([, value]) => value === lookUpMyOwnName);
if (!pair) {
return "I can't seem to find out";
}
return `My name is: ${pair[0]}`
}
const obj = {
foo: fn
}
console.log(obj.foo());
console.log(obj.foo.call(null));
console.log(obj.foo.call("some string"));
console.log(obj.foo.call({
other: "object"
}));
This is pretty close to the perfect solution. As we can see, it even works if the function is not defined as part of the object but added later. So, it's completely divorced from what object it's part of. The problem is that it's still one function and adding it multiple times will not get the correct result:
"use strict";
const fn = function lookUpMyOwnName() {
if (typeof this !== "object" || this === null) { //in case the context is removed
return "Sorry, I don't know";
}
const pair = Object.entries(this)
.find(([, value]) => value === lookUpMyOwnName);
if (!pair) {
return "I can't seem to find out";
}
return `My name is: ${pair[0]}`
}
const obj = {
foo: fn,
bar: fn
}
console.log(obj.foo()); // foo
console.log(obj.bar()); // foo...oops
Luckily, that's easily solvable by having a higher order function and creating lookUpMyOwnName on the fly. This way different instances are not going to recognise each other:
"use strict";
const makeFn = () => function lookUpMyOwnName() {
// ^^^^^^ ^^^^^
if (typeof this !== "object" || this === null) { //in case the context is removed
return "Sorry, I don't know";
}
const pair = Object.entries(this)
.find(([, value]) => value === lookUpMyOwnName);
if (!pair) {
return "I can't seem to find out";
}
return `My name is: ${pair[0]}`
}
const obj = {
foo: makeFn(),
bar: makeFn()
}
console.log(obj.foo()); // foo
console.log(obj.bar()); // bar
Making really sure we find the key
There are still ways this could fail
If the call comes from the prototype chain
If the property is non-enumerable
Example:
"use strict";
const makeFn = () => function lookUpMyOwnName() {
// ^^^^^^ ^^^^^
if (typeof this !== "object" || this === null) { //in case the context is removed
return "Sorry, I don't know";
}
const pair = Object.entries(this)
.find(([, value]) => value === lookUpMyOwnName);
if (!pair) {
return "I can't seem to find out";
}
return `My name is: ${pair[0]}`
}
const obj = {
foo: makeFn()
}
const obj2 = Object.create(obj);
console.log(obj.foo()); // foo
console.log(obj2.foo()); // unknown
const obj3 = Object.defineProperties({}, {
foo: {
value: makeFn(),
enumerable: true
},
bar: {
value: makeFn(),
enumerable: false
}
})
console.log(obj3.foo()); // foo
console.log(obj3.bar()); // unknown
Is it worth making an overengineered solution that solves a non-existing problem just to find everything here?
Well, I don't know the answer to that. I'll make it anyway - here is a function that thoroughly checks its host object and its prototype chain via Object.getOwnPropertyDescriptors to find where exactly it was called from:
"use strict";
const makeFn = () => function lookUpMyOwnName() {
if (typeof this !== "object" || this === null) {
return "Sorry, I don't know";
}
const pair = Object.entries(Object.getOwnPropertyDescriptors(this))
.find(([propName]) => this[propName] === lookUpMyOwnName);
if (!pair) {//we must go DEEPER!
return lookUpMyOwnName.call(Object.getPrototypeOf(this));
}
return `My name is: ${pair[0]}`;
}
const obj = {
foo: makeFn()
}
const obj2 = Object.create(obj);
console.log(obj.foo()); // foo
console.log(obj2.foo()); // foo
const obj3 = Object.defineProperties({}, {
foo: {
value: makeFn(),
enumerable: true
},
bar: {
value: makeFn(),
enumerable: false
},
baz: {
get: (value => () => value)(makeFn()) //make a getter from an IIFE
}
})
console.log(obj3.foo()); // foo
console.log(obj3.bar()); // bar
console.log(obj3.baz()); // baz
Use a proxy (slight cheating)
This is an alternative. Define a Proxy that intercepts all calls to the object and this can directly tell you what was called. It's a bit of a cheat, as the function doesn't really lookup itself but from the outside it might look like this.
Still probably worth listing, as it has the advantage of being extremely powerful with a low overhead cost. No need to recursively walk the prototype chain and all possible properties to find the one:
"use strict";
//make a symbol to avoid looking up the function by its name in the proxy
//and to serve as the placement for the name
const tellMe = Symbol("Hey, Proxy, tell me my key!");
const fn = function ItrustTheProxyWillTellMe() {
return `My name is: ${ItrustTheProxyWillTellMe[tellMe]}`;
}
fn[tellMe] = true;
const proxyHandler = {
get: function(target, prop) { ///intercept any `get` calls
const val = Reflect.get(...arguments);
//if the target is a function that wants to know its key
if (val && typeof val === "function" && tellMe in val) {
//attach the key as ##tellMe on the function
val[tellMe] = prop;
}
return val;
}
};
//all properties share the same function
const protoObj = Object.defineProperties({}, {
foo: {
value: fn,
enumerable: true
},
bar: {
value: fn,
enumerable: false
},
baz: {
get() { return fn; }
}
});
const derivedObj = Object.create(protoObj);
const obj = new Proxy(derivedObj, proxyHandler);
console.log(obj.foo()); // foo
console.log(obj.bar()); // bar
console.log(obj.baz()); // baz
Take a peek at the call stack
This is sloppy and unreliable but still an option. It will be very dependant on the environment where this code, so I will avoid making an implementation, as it would need to be tied to the StackSnippet sandbox.
However, the crux of the entire thing is to examine the stack trace of where the function is called from. This will have different formatting in different places. The practice is extremely dodgy and brittle but it does reveal more context about a call than what you can normally get. It might be weirdly useful in specific circumstances.
The technique is shown in this article by David Walsh and here is the short of it - we can create an Error object which will automatically collect the stacktrace. Presumably so we can throw it and examine it later. Instead we can just examine it now and continue:
// The magic
console.log(new Error().stack);
/* SAMPLE:
Error
at Object.module.exports.request (/home/vagrant/src/kumascript/lib/kumascript/caching.js:366:17)
at attempt (/home/vagrant/src/kumascript/lib/kumascript/loaders.js:180:24)
at ks_utils.Class.get (/home/vagrant/src/kumascript/lib/kumascript/loaders.js:194:9)
at /home/vagrant/src/kumascript/lib/kumascript/macros.js:282:24
at /home/vagrant/src/kumascript/node_modules/async/lib/async.js:118:13
at Array.forEach (native)
at _each (/home/vagrant/src/kumascript/node_modules/async/lib/async.js:39:24)
at Object.async.each (/home/vagrant/src/kumascript/node_modules/async/lib/async.js:117:9)
at ks_utils.Class.reloadTemplates (/home/vagrant/src/kumascript/lib/kumascript/macros.js:281:19)
at ks_utils.Class.process (/home/vagrant/src/kumascript/lib/kumascript/macros.js:217:15)
*/
I have been learning how to use classes in JavaScript, and something that always confused me was the how getters and setters work. I think I now finally understand them, is the below explanation correct?
They are no different to normal methods, and simply provide an alternative syntax.
A getter is simply an alternative to a method which cannot have a parameter, and means you don't have to use () to call, e.g.:
get myGetter() { return { msg: "hello" } };
...
classInstance.myGetter.msg; // "hello"
Is equivalent to:
myGetter() { return { msg: "hello" } };
...
classInstance.myGetter().msg; // "hello"
A setter is simply an alternative for a method that does take a parameter, e.g.:
set mySetter(value) { this.value = value };
...
classInstance.mySetter = "hello";
Is equivalent to:
mySetter(value) { this.value = value };
...
classInstance.mySetter("hello");
Functionally, that explanation is mostly correct, however they also have a more semantic meaning. Getters/setters are very useful for updating things that depend on a value or calculating a value, but they shouldn't be used for triggering actions. For example, this is a wrong usage of a getter:
const alerter = new Alerter;
// [...]
alerter.alert = "Hi there!"; // Alerts "Hi there!"
This is a good one:
const player = new Player;
// [...]
player.health--; // Also updates the health bar
It's also worth noting that, while in most circumstances, they behave like methods, they aren't methods at all! They are part of properties.
In JS, properties can have data descriptors and accessor descriptors. Data descriptors are "normal" properties. They have a value and you can get/set it.
const obj = {
prop: 1;
};
console.log(obj.prop); // Get; logs 1
obj.prop = 2; // Set
Accessor descriptors don't hold a value, and allow for setting what happens when the property is get and set.
const obj = {};
Object.defineProperty(obj, "prop", {
get() {
console.log("Getter was called");
return 1;
},
set(v) {
console.log("Setter was called with the value %o.", v)
}
});
/* Alternative syntax:
class Example {
get prop() {
console.log("Getter was called");
return 1;
}
set prop(v) {
console.log("Setter was called with the value %o.", v)
}
}
const obj = new Example;
*/
console.log(obj.prop); // Get; logs 1
obj.prop = 2; // Set
That code logs:
Getter was called
1
Setter was called with the value 2.
There is a huge difference between getters/setters and normal properties, in their most simple form you could think of them as an alternative syntax. however getters/setters provide more convenient solutions for certain use cases - though eventually getters/setters and methods are properties, getters/setters has accessor descriptors while methods has data descriptors.
I'm gonna list some few use cases on top of my head
getters/setters enable you to trigger custom functionality when reading/setting a property without having to create two different methods
let xThatShouldBeHidden = 1;
const object = {
get x() {
return xThatShouldBeHidden
},
set x(newX) {
if (newX === 0) {
throw new Error('You can not set x to 0')
}
xThatShouldBeHidden = newX
}
}
Triggering custom functionality is a cool feature, it enables you to do optimizations while still abstracting that behind simple syntax.
Imagine you you have array of items that has values, and later you want to get the weight of the item (value / sum of all values of items)
const items = [{val: 2}, {val:4}]
one way to do it would be which required you to loop twice even if eventually the weight was read from only one item
const totalSum = items.reduce((acc,cur), acc + cur.val,0));
const itemsWithWeights = items.map(item => ({...item, weight: item.val / totalSum});
now with getters we do it in one loop plus number of actual reads
const getItemsWithWeightsGetter = () => {
let totalSum;
return items.map(item => ({
...item,
get weight() {
if (totalSum === undefined) {
totalSum = items.reduce((acc, cur) => acc + cur.val, 0);
}
return item.val / totalSum;
},
}));
};
const itemsWithWeightsGetter = getItemsWithWeightsGetter();
another use case is the example i just shared above, when you provide just a getter that makes the value read only, making code throws when you try to set the value - in strict mode only
The difference is, you can have a getter/setter pair with the same name. For example, when working with DOM, there is the innerHTML getter/setter pair.
const element = document.querySelector("div")
console.log(element.innerHTML) // Outputs HTML as string
element.innerHTML = "Hello!" // Sets the HTML of element to "Hello!"
var obj = {};
console.log(obj.constructor === Object); // true
console.log(typeof obj.constructor); // function
obj['foo'] = 'bar';
obj['constructor'] = 'String';
console.log(obj.constructor === Object); // false
console.log(typeof obj.constructor); // string
I want to mention a case in this example: In the obj object, I've added a new property name constructor with value String. And the type of value is string.
So: 'string' !== 'function'.
Since I override it as the second, I cannot use it like a function as the first.
That also means: some js developers (almost) don't want to declare a property which the name is constructor in an object. If I try to doing that, the default constructor would be overridden.
Same to another case:
var array = [];
console.log(typeof array.forEach); // function
array['forEach'] = 'String';
console.log(typeof array.forEach); // string
Why doesn't js accept multiple keys with same name but difference value types?
What I want to achieve:
var action = {
isDone: false,
isDone: function (flag) {
this.isDone = flag
}
};
action.isDone(progressing is done);
if (action.isDone) {
// done...
}
// 'boolean' !== 'function'
My questions:
1/. How to define new property to an object with same key? (not duplicate with another topics because same key but differnce value types);
2/. Is it the best way to prevent to override an object property? (Or readonly as the title)
var obj = {};
Object.defineProperty(obj, 'constructor', {
get: function () {
return function () {
// default constructor here...
}
},
set: function (newValue) {
// do nothing here...
}
})
var obj = {
};
// being explicit
Object.defineProperty(obj, 'testFunction', {
writable: false,
value: function(){
console.log("Print read only Function");
return;
}
});
console.log(obj.testFunction.toString());
obj.testFunction();
obj.testFunction= function(){
console.log("Override Function");
}
console.log(obj.testFunction.toString());
obj.testFunction();
How to define new property to an object with same key? (not duplicate with another topics because same key but differnce value types);
You can't
Is it the best way to prevent to override an object property?
Sure, but you're still probably using it wrong. And whatever code you write around it is probably bad JavaScript.
Whatever language you're coming from, I suggest do not try to implement other idioms in JavaScript. JavaScript is its own thing. Learn how to write idiomatic JavaScript.
In Javascript, it seems like using property accessors is not all that common (unlike in other OO languages such as Java for example).
If I have a Person object with a name, defined as
function Person(name) {
this.name = name;
}
A person's name is not going to change, but I do want to be able to access it when needed, so I could do something like:
function Person(name) {
var name = name;
this.getName = function() {
return name;
}
}
Even in a dynamic language, I think the principles of using getters and setters apply the same way they do to statically typed OO languages (e.g. encapsulation, adding validation, restricting access, etc)
This question may get closed as subjective, but I'm curious as to why this behavior doesn't appear more often (e.g. Java developers would go crazy if everything was public).
Is there a "standard" way to do this in javascript? I've seen Object.defineProperty, but not all browsers support that.
Javascript has intercept-able property accessors:
http://ejohn.org/blog/javascript-getters-and-setters/
IMHO this is a far better solution to enforce the Uniform Access Principle than Java's more strict explicit getters, but that is also part of the simplicity and inflexibility of that language (Groovy for instance allows for similar interception).
I know my thoughts on the subject.
Getters and setters are evil.
Wait! Really! Bear with me a moment and let me explain.
Just using a method to get and set a value is .. well .. kinda pointless. It doesn't protect, not really, and what you put in is what you get out.
On the other hand, I'm rather fond of methods that put information in, then get information back out. BUT here is the magic part! It isn't the same information. Not directly.
function Person(name) {
this.getFullName = function() {return this.firstName + " " + this.lastName;};
this.setBirthday = function(date) { this.birthday = date; };
this.getAge = function() { /* Return age based on the birthday */ };
this.isOfLegalDrinkingAge function() { /* do your math here too */ };
}
But most of the time I'm just shoving static data in and getting static data out. What is the point of hiding it behind getters and setters?
As a secondary reason, dealing with the DOM and most host objects, you set properties. You don't play with getters and setters. Not using them fits the rest of the 'flavor' of what JS coders do.
I think the answer is that emulating classes in javascript is not the common practice, because the language is actually prototypal.
Although it is possible to create class like structures (as in your example), they are not really like java classes, and as a programmer, you end up fighting with the nuances.
If however, you embrace the prototypal nature of javascript, you are rewarded by a different, yet cohesive, and simple structure for the language.
It is not necessary to use getters and setters with prototypal structure, as you can simply set an object by, well, setting it to a value, and get it by, calling it as a value.
Javascript does not force you to write structured code, and does not stop you from doing so. I think the culture that has grown up around javascript has developed a good coding style, that is perfectly valid, and different from any other language I use.
I know this answer is not definitive, and conclusive, but hopefully there are some ideas in there that help you to find the anser you are looking for.
I apologize if I dont understand the question correctly, but self executing functions are one way to make members public/private
var Person = function(){
var _name = "Roger",
self = { getName : function (){ return _name; }};
return self;
}()
You can then access Person.getName() from anywhere , but not set _name.
This is what I used for local fields:
TYPE_DEFAULT_VALUE= {
number: 0,
string: "",
array: [],
object: {},
};
typeOf = function (object) {
if (typeof object === "number" && isNaN(object))
return NaN;
try {
return Object.prototype.toString.call(object).slice(8, -1).toLowerCase();
}
catch(ex) {
return "N/A";
};
};
getAccessor = function(obj, key, type, defaultValue) {
if (defaultValue === undefined)
defaultValue = TYPE_DEFAULT_VALUE[type] === undefined ? null : TYPE_DEFAULT_VALUE[type];
return {
enumerable: true,
configurable: true,
get: function () {
if (obj[key] === undefined)
obj[key] = defaultValue;
return obj[key];
},
set: function (value) {
if (typeOf(value) === type)
obj[key] = value;
},
};
}
LocalFields = function (fields, object) {
/**
* field properties
* {
* type: [ required ] ( number | string | array | object | ... ),
* defaultValue: [ optional ]
* }
*/
if (! fields)
throw "Too few parameters ...";
if (! object)
object = this;
var obj = this;
var fieldsAccessor = {};
for(key in fields){
field = fields[key];
fieldHandler = key[0].toUpperCase() + key.substr(1);
if(! field.type)
throw "Type not set for field: " + key;
fieldsAccessor[fieldHandler] = getAccessor(obj, fieldHandler, field.type, field.defaultValue)
}
Object.defineProperties(object, fieldsAccessor);
}
Now for each Class I can just call something like:
Person = function(){
new LocalFields({
id: { type: "number" },
name: { type: "string" },
}, this);
}
And then like VS getter and setter you'll call:
var alex = new Person();
alex.Name = "Alex Ramsi";
console.clear();
console.info(alex.Name);
How can I specify a default getter for a prototype?
With default getter I mean a function that is called if obj.undefinedProperty123 is called.
I tried Object.prototype.get = function(property) {..} but this is not called in this case.
In ECMAScript 5, you can only intercept get/set operations on specific named properties (not universally all properties) via Object.defineProperty:
Object.defineProperty(someObj, "someProp", {
get: function() {
console.log("you tried to get someObj.someProp");
return "foo";
}
});
Here, the get function will run any time code tries to read someObj.someProp.
In the upcoming ECMAScript 6 draft, this will be possible via proxies. A proxy has an underlying target object and set/get functions. Any time a set or get operation happens on any of a proxy's properties, the appropriate function runs, taking as arguments the proxy's target object, property name used, and the value used in a set attempt.
var proxyHandler = {
get: function(obj, name){
console.log("you're getting property " + name);
return target[name];
},
set: function(obj, name, value) {
console.log("you're setting property " + name);
target[name] = value;
}
}
var underlyingObj = {};
// use prox instead of underlyingObj to use get/set interceptor functions
var prox = new Proxy(underlyingObj, proxyHandler);
Here, setting to getting property values on prox will cause the set/get functions to run.
What Gareth said, except it's __noSuchMethod__.
Or maybe you were thinking of PHP?
Here's a very good article on the recently standardized property getters/setters, highlighting some previous non-standard incarnations.
http://whereswalden.com/2010/04/16/more-spidermonkey-changes-ancient-esoteric-very-rarely-used-syntax-for-creating-getters-and-setters-is-being-removed/
summary: there's no standard 'catch-all' getter / setter (yet), but Object.defineProperty is the future.
You need to wait for the implementation of the ECMA6 "Proxy" system, designed to do exactly this. See http://wiki.ecmascript.org/doku.php?id=harmony:direct_proxies.
You want to create a Proxy:
const data = {};
const proxy = new Proxy(data, {
get: (target, prop) => {
console.log({ target, prop });
return "My Value";
},
set: (target, prop, value) => {
console.log({ target, prop, value });
return true;
},
});
proxy["foo"] = "bar";
const bar = proxy["foo"];
Firefox it's possible with non-standard noSuchMethod:-
({__noSuchMethod__:function(){alert(1);}}).a();
I am not sure about what you are asking. But If you want a method to be called when the user attempts to Access object.nonExistingProperty . I dont think there is any way to do that.
maybe late to ther party, let just add simple ES5 friendly "class creation": both string props and getters - i needed it for some ancient rewrite, to temporarily support IE (yes, that hurts, still found someone relying on ActiveX)
var MyObj = function () {
var obj = {
url: 'aabbcc',
a: function(){ return this.url;}
}
Object.defineProperty(obj, "urltoo", { get: function () { return this.url; } })
return obj;
}
var X = new MyObj();
x.url // aabbcc
x.urltoo // aabbcc
x.urltoo() // error - not a function
x.a() // aabbcc
x.a // ƒ (){ return this.url;}
I ran into this question because I wanted this behavior: if object property is undefined, return some default value instead.
const options = {
foo: 'foo',
bar: 'bar',
baz: 'baz'
};
function useOptionValue(optionName) {
// I want `options` to return a default value if `optionName` does not exist
const value = options[optionName];
// etc...
}
The simple way to do this (without Proxy or Object.defineProperty overkill for this use case) is like so:
function useOptionValue(optionName) {
const value = options[optionName] || defaultValue;
}
Or, if you want to get fancy, you could use a Symbol:
const default = Symbol.for('default');
const options = {
foo: 'foo',
bar: 'bar',
baz: 'baz',
[default]: 'foobarbaz'
};
function useOptionValue(optionName) {
const value = options[optionName] || options[default];
}