Javascript调用同一对象内的对象方法不能正常工作

时间:2015-12-20 15:21:03

标签: javascript

在这个theme对象中,我创建了2个属性。

我将this.changeThemeTo(1);置于事件监听器下,之后就可以了。但我想将其放在if标记

但是将它放在if

中似乎会出错
  

未捕获的TypeError: this.changeThemeTo 不是函数

请帮助解决这个问题。感谢..

var theme = {
    changeThemeTo: function (theme_value) {
        sessionStorage.removeItem('THEME'); // remove old theme from session storage
        if (theme_value == 0) {
            sessionStorage.setItem("THEME", 'dark');
        } else if (theme_value == 1) {
            sessionStorage.setItem("THEME", 'light');
        }
        document.body.className = sessionStorage.getItem("THEME");
    },
    init: function () {
        document.body.classList.add("fade");
        setTimeout(function () {
            document.body.classList.remove("fade");
        }, 100);

        var themes = ['dark', 'light'];

        themes.forEach(function (item) {
            var button = document.querySelector("." + item);

            if (button) {
                button.addEventListener("click", function () {
                    if (item == "dark") {
                        this.changeThemeTo(0);
                    } else if (item == "light") {
                        this.changeThemeTo(1);
                    }
                });
            }
        }, this);
    }
}
window.onload = function () {
    theme.init();
}

这里是我的HTML代码

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
    .dark {
    background-color: #191919;
    color: #EEEEEE;
}
.light {
    background-color: #EEEEEE;
    color: #191919;
}
</style>
</head>
<body>
<div id="change-theme">
    <a href="javascript:;" class="dark">DARK</a>
    <a href="javascript:;" class="light">LIGHT</a>
</div>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

使用self.changeThemeTo代替this.changeThemeTo。并根据下面的代码示例定义self = this。还优化了部分代码。

var theme = {
    changeThemeTo: function (theme_value) {
        sessionStorage.setItem("THEME", theme_value);
        document.body.className = theme_value;
    },
    init: function () {
        document.body.classList.add("fade");
        setTimeout(function () {
            document.body.classList.remove("fade");
        }, 100);

        var themes = ['dark', 'light'];
        var self = this;

        themes.forEach(function (item) {
            var button = document.querySelector("." + item);

            if (button) {
                button.addEventListener("click", function () {
                     self.changeThemeTo(item);
                });
            }
        }, this);
    }
}
window.onload = function () {
    theme.init();
}
 <style type="text/css">
    .dark {
    background-color: #191919;
    color: #EEEEEE;
}
.light {
    background-color: #EEEEEE;
    color: #191919;
}
</style>
<div id="change-theme">
    <a href="javascript:;" class="dark">DARK</a>
    <a href="javascript:;" class="light">LIGHT</a>
</div>