繁体   English   中英

JavaScript范围问题-变量未定义

[英]Javascript scope issue - variable is undefined

我对此感到有些困惑,因为我确信所有变量在运行时都被带到javascript的“顶部”,然后从那里进行处理。

所以我的错误

 TypeError: hutber.portfolio.ko is undefined
 [Break On This Error]  
 items: ko.observableArray(hutber.portfolio.ko.data),

宾语

(function ($) {
"use strict"; //For good development standards :)
hutber.portfolio = {
    init: function(){
        e(typeof(hutber));
        hutber.portfolio.changeOptionsBoxHeight();
        //Bind the height resize in window resize
        $(window).resize(function(){
            hutber.portfolio.changeOptionsBoxHeight();
        });
        //start KO
        hutber.portfolio.ko.init();
    },
    changeOptionsBoxHeight: function(){
        var height = $(window).height();
        $('.portfolio--options').height(height-400);
    }
};
hutber.portfolio.ko = {
    init: function(){
        ko.applyBindings(new hutber.portfolio.ko.portfolioViewModel());
    },
    data: [],
    items: ko.observableArray(hutber.portfolio.ko.data),
    portfolioViewModel: function(){

        hutber.portfolio.ko.items = ko.observableArray(hutber.portfolio.ko.data);

        $.getJSON('/js/pages/portfolio.json').done(function(info){
            hutber.portfolio.ko.data = info;
            hutber.portfolio.ko.items (hutber.portfolio.ko.data);
        });
    }
};
hutber.portfolio.init();
})(jQuery);

我确实想将其上传到一个小提琴,但是由于某种原因,我在他们的网站上遇到了js错误。 我相信我的防火墙阻止了某些文件的加载。

在运行ko.observableArray(hutber.portfolio.ko.data) ,尚未定义hutber.portfolio.ko

您可以像这样解决它:

hutber.portfolio.ko = {
    init: function(){
        ko.applyBindings(new hutber.portfolio.ko.portfolioViewModel());
    },
    data: [],
    portfolioViewModel: function(){

        hutber.portfolio.ko.items = ko.observableArray(hutber.portfolio.ko.data);

        $.getJSON('/js/pages/portfolio.json').done(function(info){
            hutber.portfolio.ko.data = info;
            hutber.portfolio.ko.items (hutber.portfolio.ko.data);
        });
    }
};

hutber.portfolio.ko.items = ko.observableArray(hutber.portfolio.ko.data);

但是此时hutber.portfolio.ko.data始终为[] 因此,您最好将ko.observableArray([])放入原始代码中。

只需猜测:因为您在声明变量之前就访问了它?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM