首页 > 解决方案 > 如何跨对象执行函数与使用 this 引用执行函数本身相同

问题描述

我正在开发一个模块化的 Web 应用程序,其根组件是编辑器对象。此 Editor 对象处理多个组件的创建。这些组件对象之一是 Filebar 组件,它能够从 Editor 对象中引用函数。由于文件栏中的菜单中有很多按钮,因此我在代码中创建了一个名为“index”的表,用于引用 Editor 对象中的函数。我能够获得对函数本身的引用,但是我在执行函数时遇到了麻烦,就好像它是在原始对象本身中执行的一样。所以这是我的问题:

问题 1:如果我从 Filebar 对象调用函数以便将正确的“this”传递给我正在创建的新 Inspector,如何正确引用 Editor 对象?

问题 2:(一个有希望的小问题)在下面的代码中显示的表格中为我的事件侦听器引用函数是一种好习惯吗?

function Editor() {

    // Initializes the Object. Called at end.
    this.Initialize = function() {
        thisCreateFileBar();
    }


    this.createFilebar = function(){
        this.file = new Filebar(this);
    };

    // Creates a Scene Object. 
    this.createScene = function() {
        this.scene = new Scene(this);
    };

    // Create an Inspector.
    this.createInspector = function(){
        this.inspector = new Inspector(this);
    };

    // Create a Hierarchy.
    this.createHierarchy = function(){
        this.hierarchy = new Hierarchy(this);
    };

    let thisCreateFilebar = this.createFilebar.bind(this);
    let thisCreateInspector = this.createInspector.bind(this);
    let thisCreateHierarchy = this.createHierarchy.bind(this);
    let thisCreateScene = this.createScene.bind(this);

function Filebar(editor){

    // Initializes the Object. Called at end.
    this.Initialize = function(){
        this.editor = editor;
        this.menu = document.getElementById("Engine_UI:Menu");
        this.menu.addEventListener("mouseup", thisChoice);
    }

    this.choice = function(event){
        // Question 2 Should I be referencing functions for my event listeners like this? 
        let index = {
            "Add Inspector": this.editor.createInspector,
            "Add Hierarchy": this.editor.createHierarchy,
            "Add Scene": this.editor.createScene
        };

        let element = event.target;
        if (element.innerHTML != null){
            let func = index[element.innerHTML];
            func(this.editor);
        } else return;
        event.stopPropagation();
    }

    let thisChoice = this.choice.bind(this);
    this.Initialize();
}

function Inspector(editor){
    console.log(editor) // Question 1 When passed directly from the editor object 
    // which passes in a reference to this, it passes itself
    // but when referenced from filebar it references the Window instead. 

    //other stuff happens here.
}

我为完成这项工作所做的一件事是传入一个额外的变量以供参考。这最终以我希望的方式工作,但在我看来,这感觉有点 hacky,我想看看是否有一种方法可以正确绑定对象以使其工作。或者也许传入一个变量会比使用 this 引用更好,我不确定。请让我知道你的想法!

标签: javascript

解决方案


为了传递this给这些函数,您有两个选择:

var myEditor = this;

this.createFilebar = function(){
    myEditor.file = new Filebar(myEditor);
};

或者您可以使用 lambda 函数,这将保留 this-ness。

this.createFileBar = () => this.file = new FileBar(this);

推荐阅读