Setter for dynamic property in javascript

I am wondering if it is possible to set a dynamic property tool in Javascript?

So this is:

var myobj = new MyObj(); myobj.a_custom_prop = 'something'; 

Calling a function capable of retrieving 'a_custom_prop' and 'something'

To be clear, I need a function like this:

 MyObj.property.define = function (prop, value) { }; 

will be called as follows:

 myobj.prop = value; 

instead:

 myobj.define('prop', value); 

Knowing that the property name is not static with respect to myobj , otherwise I would use:

 Object.defineProperty(MyObj.prototype, 'a_custom_prop', { set: function (value) { /*...*/ } }); 
+8
javascript
source share
4 answers

What you want is similar to method missing in Ruby, where you define a function that processes undefined method calls.

As you can read here: Does Javascript have something like a method_missing Ruby function? JavaScript doesn't have something similar yet, but there is a suggestion for ES6: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy

+4
source share

As Yoshi stated in a comment, this is possible using Object.observe() from the ES7 project.

However, this is not exactly a "catcher", because it will be called only after the property has changed, and not earlier. So, if you want to save the property somewhere else, you will need to delete it. Since the observe is asynchronous, it will be launched after the current call, which means that the new value can be used immediately before the change.

In addition, Chrome is just now.

The following snippet does some manipulation of the object using the built-in parameter and uses Object.observe . It is registered in the following order:

  • I added this value: foobar
  • Callback Retrieves: foobar
  • Foo.bar value after deletion: undefined

Here:

 var foo = {}; Object.observe(foo, function(changes) { var lastChanges = changes[changes.length - 1], newValue = lastChanges.object[lastChanges.name]; console.log('The callback retrieves: ' + newValue); delete lastChanges.object[lastChanges.name]; }, ['add']); foo.bar = 'foobar'; //Log n°2 console.log('I added this value: ' + foo.bar); //Log n°1 setTimeout(function() { console.log('Value of foo.bar after deletion: ' + foo.bar); //Log n°3 }, 0); //Execute after the observe callback 

Due to the fact that in the ES7 project, the previous one may be completely wrong depending on when you read this.

+2
source share

Could you use something like this?

 function MyObj(){ ... this.dynamicPropertyName = 'something'; ... } MyObj.prototype.setThatProp = function(i){ this[this.dynamicPropertyName] = i; } ... var myObj = new MyObj(); myObj.setThatProp(5); 

EDIT:

Or something like this:

 MyObj.prototype.__defineSetter__('prop', function(val){ this[this.dynamicPropertyName] = val; }); ... var myObj = new MyObj(); myObj.prop = 5; 

Usage example:

console test

0
source share

No, this is currently not possible.

-one
source share

All Articles