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?
callTo.prototypeisundefined. I'm not even sure why you'd attempt to change it here, though - seems like an XY problem.this, there are other approaches.callTo = function() { return {scream: this.xxxxx}}.bind(template), but that made me access 'scream' as callTo().scream (notice parenthesis)callTo = (function() { return {scream: this.xxxxx}}.bind(template))()would allow you to docallTo.screamif that's what you wish. Although if you need this multiple times I'd probably do something more likemakeCall = function(template) { return { scream: template.xxxx } }and then you'd reuse it ascallTo = makeCall(template). With a module pattern you can also declareself = templateand useself(or whatever name you choose) instead ofthisin methods. I don't see what you're trying to accomplish here. It seems like the Y is too complex but I don't know what the X is.