Javascript范围问题

时间:2014-01-16 22:31:29

标签: javascript scoping

我以为我明白javascript范围到目前为止是如何工作的。这就是我所拥有的

function MFCommentsHandler(node, type, item) {
    this.get = function(returnType){
        ...
    }

    function getButton(){
        var button = document.createElement('button'),
            get = this.get;
        button.innerHTML = 'Load more comments';
        button.onclick = function(){
            console.log(get);
            get('html');
        }
        return button;
    }

}

我使用内部函数将getButton生成的元素附加到文档中,但是当我单击它时,我得到get is not a function。为什么在get函数内部onclick未定义?

3 个答案:

答案 0 :(得分:2)

this仅取决于您如何调用函数。它可以是隐含的,但在您的情况下,您丢失了上下文。您需要在上限范围内缓存this

function MFCommentsHandler(node, type, item) {
    var self = this;
    this.get = function(returnType){
        ...
    }
    function getButton(){
        self.get(); // cached reference
        ...
    }
}

或者,当您致电getButton时,您可以明确传递上下文:

function MFCommentsHandler(node, type, item) {
    this.get = function(returnType){
        ...
    }
    function getButton(){
        this.get();
        ...
    }
    getButton.call(this); // explicit context
    ...

答案 1 :(得分:2)

this的反叛因上下文而改变。试试这个:

function MFCommentsHandler(node, type, item) {
    var get = function(returnType){
        ...
    }

    function getButton(){
        var button = document.createElement('button');
        button.innerHTML = 'Load more comments';
        button.onclick = function(){
            console.log(get);
            get('html');
        }
        return button;
    }

}

答案 2 :(得分:1)

您在定义的getButton()函数中定义的MFCommentsHandler()函数是一个闭包。闭包可以访问其外部函数的变量和参数(但不是arguments对象)。但是,它们无法访问其外部函数的this值。要访问此值,只需将其引用存储在变量中,以便可以从内部函数访问它。

function MFCommentsHandler(node, type, item) {
    var that = this; //reference to the invocation context
    //that can be accessed anywhere within this function

    this.get = function(returnType){
        ...
    }

    function getButton(){
        ...
        that.get('html');
    }

}