Javascript作用域问题-变量未定义

Javascript scope issue - variable is undefined

本文关键字:变量 未定义 问题 作用域 Javascript      更新时间:2023-09-26

我对此有点困惑,因为我确信所有变量在运行前都被带到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([])放在原始代码中。

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