Home > Net >  Can Javascript do dynamic properties like Swift's @dynamicMemberLookup?
Can Javascript do dynamic properties like Swift's @dynamicMemberLookup?

Time:10-15

In Swift we have @dynamicMemberlookup which lets us dynamically reference a property without having to first define it. Great for situations where keys names on things like maps are not known in advance. For example I can do something like this:

object.abc = 5
object.abc // -> 5

And the compiler will call a pre-defined function:

subscript(dynamicMember member: String) -> Int {
    get { return someMap[member] }
    set { someMap[member] = newValue
}

Effectively it's syntactical sugar. But what I'm doing at the moment is calling some user supplied Javascript from my Swift app and as part of that call I'm passing an object to the javascript which can be used to get and retrieve values.

At the moment I've defined function get(key) {...} and function set(key, value) {...} functions on the object I'm passing. This allows:

object.set("abc", 5);
object.get("abc"); // -> 5

But I'd really like the javascript to be able to do a dynamic property without knowing the name of it in advance. ie:

object.abc = 5;
object.abc; // -> 5

I've looked around but I can't see if this is possible in Javascript. Is it?

Edit

ultimately the object I pass to the javascript is a Swift object and the get and set functions I defined in the javascript are actually routing to the backing Swift object in a dynamic manner. That means that when I call the javascript I don't have to pass every single value currently stored. Which could be a large amount.

CodePudding user response:

Not sure I follow you but is this what you want ?

let propName = 'abc' ;
object[propName] = 5 
console.log(object[propName]) ;

you can change the property name to anything you want and it will just create, set and retrieve that property

CodePudding user response:

So what I think I'm trying to ask :-) if when the javascript does:

object.abc = 5

How can I detect that and call the function set(key, value) {...} code?

  • Related