En el siguiente código, obtengo una referencia indefinida para this.lister en el método create_components . Estoy tratando de entender el significado de this (aparentemente cambia según cómo llame al método), pero sería genial si alguien pudiera señalar la regla por la que this no se vincula con ScreenCreator y cómo puedo lograrlo.
¡Gracias!
function ScreenCreator(config, container) { this.lister = new Lister(); this.goldenlayout = new GoldenLayout(config, container); this.create_components(); this.goldenlayout.init(); } ScreenCreator.prototype.create_components = function() { this.goldenlayout.registerComponent('comp1', function (container, state) { this.lister.init(container, state); }); }Cree una variable en la parte exterior (normalmente la llamo self , pero cualquier cosa funciona) y utilícela en el interior.
function ScreenCreator(config, container) { this.lister = new Lister(); this.goldenlayout = new GoldenLayout(config, container); this.create_components(); this.goldenlayout.init(); } ScreenCreator.prototype.create_components = function() { const self = this; this.goldenlayout.registerComponent('comp1', function (container, state) { self.lister.init(container, state); }); } Alternativamente, puede usar una función de flecha, ya que no crean su propio this contexto.
ScreenCreator.prototype.create_components = function() { this.goldenlayout.registerComponent('comp1', (container, state) => { this.lister.init(container, state); }); } Si desea una forma extraña de hacerlo, que probablemente no debería usar a menos que los demás no funcionen, esto es lo siguiente: (agregando .bind(this) después de la función)
ScreenCreator.prototype.create_components = function() { this.goldenlayout.registerComponent('comp1', (function (container, state) { this.lister.init(container, state); }).bind(this)); }Podrías almacenar this in a variable como
ScreenCreator.prototype.create_components = function() { let screenCreatorThis = this this.goldenlayout.registerComponent('comp1', function (container, state) { screenCreatorThis.lister.init(container, state); }); }