I'm trying to bind the this keyword of a function and use the Function as with object dot notation (as Functions are also objects). I figured out using the object literal 'get' to do something like: myFunction.whatever (instead of myFunction().whatever).

Code is:

let template = {name: "William"};
let aux = function(){}
callTo = aux.bind(template);

Object.defineProperty(callTo.prototype, "scream", {
    get: function() {
        console.log(this);
        return "Hi, " + this.name;
    }
});
myObj = new callTo();
myObj.scream;

This causes the: "Object.defineProperty called on non-object" error However, if I bind in each property defined with "get" it will correctly work.

let template = {name: "William"};
let callTo = function(){}

Object.defineProperty(callTo.prototype, "scream", {
    get: function() {
        console.log(this);
        return "Hi, " + this.name;
    }.bind(template)
});
myObj = new callTo();
myObj.scream;  // Outputs Hi William

The working approach works but obligues me to add a bind() at the end of each propery. So question is:

¿Why is first code failing?

0

There are 0 best solutions below