【问题标题】:this works on some functions and not others这适用于某些功能,而不适用于其他功能
【发布时间】:2014-10-12 19:37:32
【问题描述】:

通常在编写 jQuery 时我只使用函数。这次我想给它一点最佳实践,所以我遵循了一个教程。 javascript 本身似乎是正确的,但我在调用某些函数时遇到了一些问题。

 jQuery.noConflict();
    (function($j) {
    'use strict';

function Site(settings) {

    this.windowLoaded = false;

}

Site.prototype = {
    constructor: Site,

    start: function() {
        var me = this;

        $j(window).load(function() {
            me.windowLoaded = true;
        });

        this.attach();
    },

    attach: function() {
        this.getPrimaLink();
        this.onCloseDialog();
        this.triggerDialog();
        this.openLink();
    },

    getPrimaLink: function(){
        if($j('#order-data').is(":visible")){
            $j( ".content-header" ).append($j( "#findPrimaLink" ));
            $j('#findPrimaLink').show();
        } 
    },

    onCloseDialog: function(){
        $j('#dialog').bind('dialogclose', function(event) {
            $j( ".content-header" ).append($j( "#findPrimaLink" ));
            $j('#findPrimaLink').show();
        });
    },

    triggerDialog: function(){
        $j("[title='Create New Customer']").click(function(){
            $j('#findPrimaLink').show();
        >>>>>   this.openDialog(); <<<<<<
        })
    },

    openLink: function(){
        $j('#findPrimaLink').click(function(){
        >>> this.openDialog();   <<<<<

        });
    },

    openDialog: function(){
        $j( "#dialog" ).dialog({
                height: 'auto',
                width: 350,
                modal: true,
                resizable:false,
        }); 
    },


};

$j(document).ready(function($j) {
    var site = new Site();
    site.start();
});

 })(jQuery); 

在 start 和 attach 函数中,我可以通过在其前面放置“this”来调用每个函数。但是当我尝试从 openLink() 和 triggerDialog() 调用 openDialog() 时,我得到 - Uncaught TypeError: undefined is not a function。

为什么会这样,我应该怎么做才能解决它?

【问题讨论】:

    标签: javascript jquery scope undefined


    【解决方案1】:

    对于您遇到问题的两个函数,您尝试在 jQuery 函数内部使用 this,因此 this 的范围是 DOM 元素,而不是 Site

    triggerDialog: function(){
        var site = this;
    
        $j("[title='Create New Customer']").click(function(){
            $j('#findPrimaLink').show();
            site.openDialog();
            console.log(this); //remove this for production, but you can see that `this` points to a DOM element
        })
    },
    
    openLink: function(){
        var site = this;
    
        $j('#findPrimaLink').click(function(){
            site.openDialog();
        });
    },
    

    要了解为什么会发生这种情况,您应该阅读有关 javascript Closures 的内容。 Herehere

    附: openDialog 函数后面多了一个逗号。

    附言还值得注意的是,这正是您在 start 方法中所做的。

    var me = this;
    
    $j(window).load(function() {
        me.windowLoaded = true;
    });
    

    【讨论】:

    • 非常感谢。我赞成并接受了:)
    猜你喜欢
    • 1970-01-01
    • 2011-12-16
    • 2020-02-27
    • 1970-01-01
    • 2015-11-27
    • 2014-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多