# Custom Constructor Hook vs. Subclassing

We found a way to refine/replace constructors, party!

We can modify parameters, access the resulting instance, and can execute code before and after.

<script>
import {hideHiddenElements, toggleLayer, showVariable, inspectVariable, runExampleButton} from "src/client/essay.js"
""
</script>

```javascript { .HookBase}
class A  {
  constructor(x) {
    this.x = x;
    this.a()
  } 
  a() {
    console.log("A")
  }
}
```

```javascript {.HookDef}
// There will be an object of B constructed that is thrown away
var B = function B(...args) {
  if (this.constructorHook) {
    var p = (...rest) => {
      // we may return any object here
      return new A(...rest)
    }
    return this.constructorHook(p, args)
  }
  return new A(...args)
};
// We replace the !constructor! of A here
B.prototype = A.prototype;
```

```javascript {.HookHook}
B.prototype.constructorHook = function(p, args) {
  console.log("hook")
  return p(args[0]+1)
}
```


```javascript {.HookRun}
var b = new B();
({
  b: new B(1).x, 
  a: new A(1).x
});

```

<script>runExampleButton("run with hook", this, ["HookBase", "HookDef", "HookHook","HookRun"])</script>
<script>runExampleButton("run without hook", this, ["HookBase", "HookDef","HookRun"])</script>


## Related

- <https://stackoverflow.com/questions/8530466/how-do-i-monkey-patch-an-objects-constructor-function>



