SoFunction
Updated on 2025-04-08

js defineSetter - automatically add a set attribute (method) to js' "class"

Writing comments is not my strength. If you have any questions, please write them in the comments:D

When writing a JS class,

[Ctrl+A Select all Note:Introducing external Js requires refreshing the page before execution]

To understand the code easily and to better distinguish public and private variables, I usually use the set... method (... to some member variables) to assign values ​​to members of the class. These set methods are of course public. Another point is to make the code more standardized.

However, the problem lies here. If the above code does not consider the validity of verification (or only verify the simple validity), then we will have a lot of extra code. Just imagine that a class has 20 members (attributes), then we have to add 20 set... method, which is really redundant, so we need to find a way to solve this problem.

Recalling in Mozilla, there are __defineSetter__ and __defineGetter__ methods to add members to the DOM, bringing a lot of convenience to developers. Let's also imitate a js version of __defineSetter.

Simple idea:
Use JS to dynamically add methods (or attributes) to objects
But the methods in the class do not need to add set...this method.
Non-[a-z] interval properties are added no longer set...this method.

Write implementation code

The _defineSetter is basically implemented, and it wouldn't be too troublesome to have defineSetters one by one. Since the prototype has been implemented, then using the prototype to dynamically bind to the Function object, a line of code solves the set... method.
 = function (hdle) {

  for (var i in )
  _defineSetter.apply(this, [this,i,hdle]);

  return this;

};

Next, bind a defineSetter to the Function object.

 = function (p, hdle) {

  return _defineSetter.apply(this, 
  [this].concat((arguments,0)));

};

OK! Basically complete the desired function. try it...

[Ctrl+A Select all Note:Introducing external Js requires refreshing the page before execution]
This example DEMO and all codes:
/code/js/defineSetter/

Of course, we can also add verification~, I won’t write more specific codes. Haha, it has been implemented. Interested friends also try to play with it:D.