Javascript范围问题 - 变量未定义

时间:2013-01-11 13:57:19

标签: javascript jquery scope

我对此感到有些困惑,因为我确信所有变量都会在运行时被带到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错误。我相信我的防火墙会阻止某些文件加载​​。

2 个答案:

答案 0 :(得分:1)

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([])放入原始代码中。

答案 1 :(得分:0)

猜猜:因为你在声明它之前访问变量了吗?