如何从父函数中获取“this”

时间:2014-09-02 00:33:34

标签: javascript angularjs

我正在使用angularjs构建一个简单的制表符系统,但是我在父函数中引用this时遇到了麻烦。我知道我可能会误解一些基本原则,所以请教育我:

JS:

$scope.tabs = {
    _this: this, // doesn't work
    open: function(elem) {
        $scope.tabsOpen = true; 
        if(elem) 
            $scope[elem] = true;
    },
    close: function() {
        $scope.tabsOpen = false;    
    },
    about: {
        open: function() {
            $scope.aboutOpen = true;    

            _this.notification.close(); // doesn't work
            $scope.tabs.notification.close();  // works

        },
        close: function() {
            $scope.aboutOpen = false;   
        }           
    },
    notification: {
        open: function() {/*etc*/},
        close: function() {/*etc*/}
    },
    message: {
        open: function() {/*etc*/},
        close: function() {/*etc*/}
    },
}

1 个答案:

答案 0 :(得分:0)

怎么样: -

$scope.tabs = getTab();

function getTab(){
    var tab = {
        open: function(elem) {
            $scope.tabsOpen = true; 
            if(elem) 
                $scope[elem] = true;
        },
        close: function() {
            $scope.tabsOpen = false;    
        },
        about: {
            open: function() {
                $scope.aboutOpen = true;    
                tab.notification.close(); // Should work
             },
            close: function() {
                $scope.aboutOpen = false;   
            }           
        },
        notification: {
            open: function() {/*etc*/},
            close: function() {/*etc*/}
        },
        message: {
            open: function() {/*etc*/},
            close: function() {/*etc*/}
        },
    }

    return tab ;
}

这样,您不依赖于this上下文将由执行上下文决定,而不是由它定义的位置。在这里,您只是在调用函数tab时使用在本地范围内创建的本地getTab对象,而不是执行_this.notification.close();,您只需执行tab.notification.close();,其中{{1}你真正想要的是tabA simple Demo