javascript - Why do I lose context in this code? -


here code lose context when using spread operator.

look @ function "decorator". line when lose context marked "error"

/** methoddecorator example */ class account {     public firstname: string;     public lastname: string;      public constructor(firstname: string, lastname: string) {         this.firstname = firstname;         this.lastname = lastname;     }      @decorator     public saymessage(msg: string): string {         return `${this.firstname} ${this.lastname}: ${msg}`     } }  function decorator(target: any, key: string, desc: any): {     let origindesc = desc.value;      desc.value = function(...args: any[]): {         return origindesc(...args); // ==> error: context lost         //return origindesc.apply(this, arguments); // ==> ok     };     return desc; }  let persone = new account('john', 'smith'); let message = persone.saymessage('hello world!'); console.log(message); // ==> undefined undefined: hello world! 

as far understand origindesc(...args); equals origindesc.apply(this, arguments); why context lost?

as far understand origindesc(...args); equals origindesc.apply(this, arguments); why context lost?

no, doesn't. it's equivalent origindesc(args[0], args[1], /*etc.*/), uses default this (the global object in loose mode, undefined in strict mode).

in code, you'll need use .apply:

origindesc.apply(appropriatethisvaluehere, args); 

or .call:

origindesc.call(appropriatethisvaluehere, ...args); 

according comment in code:

 //return origindesc.apply(this, arguments); // ==> ok 

appropriatethisvalue this, either:

origindesc.apply(this, args); 

or

origindesc.call(this, ...args); 

Comments

Popular posts from this blog

php - How to add and update images or image url in Volusion using Volusion API -

javascript - jQuery UI Splitter/Resizable for unlimited amount of columns -

javascript - IE9 error '$'is not defined -