函数内部调用函数JavaScript

时间:2017-08-03 22:16:13

标签: javascript

我有一些我无法理解的问题:

var Copyright =
{

    onLoad: function () {
        this.initCopyrightMoving();
    },


    initCopyrightMoving: function () {
        $(".sidebar_toggle").click(function () {
            var copyright = document.getElementById("copyright-text");

            if (copyright.className == "copyright-menu-open") {
                this.decrease(280, 80, 10, copyright);
            }

            else
                copyright.className = "copyright-menu-open"

        });
    },

    decrease: function (actual_val, stop_val, step, copyright) {
        setTimeout(function () {
            if (actual_val == stop_val) {
                copyright.className = "copyright-menu-closed";
            }
            actual_val = actual_val - step;
            copyright.style.paddingLeft = parseInt(actual_val) + "px";
            this.decrease(actual_val, stop_val, step, copyright);
        }, 10);
    }

};

当我在行initCopyrightMoving中致电this.decrease(280, 80, 10, copyright);时,我收到此错误:

copyright.js:14 Uncaught TypeError: this.decrease is not a function
    at HTMLAnchorElement.<anonymous> (copyright.js:14)
    at HTMLAnchorElement.dispatch (jquery-1.11.2.min.js:3)
    at HTMLAnchorElement.r.handle (jquery-1.11.2.min.js:3)
可以告诉我我做错了什么吗?而且因为我无法运行下一部分脚本,你能告诉我decrease函数是否写得好,我的意思是它会正常运行。

2 个答案:

答案 0 :(得分:0)

this此处是您点击的元素$(".sidebar_toggle")

尝试在jQuery处理程序之前定义var self = this;并在处理程序

中调用self.decrease this.decrease内的{p> setTimeout也不会因类似原因而起作用。修复是相同的

答案 1 :(得分:0)

这是因为this(上下文)在click回调中发生变化。一种可以阻止错误的方法是保留this的副本并在回调中使用它。

initCopyrightMoving: function() {

  var _this = this; // some developers use `self`

  $(".sidebar_toggle").click(function() {
    var copyright = document.getElementById("copyright-text");
    if (copyright.className == "copyright-menu-open") {
      _this.decrease(280, 80, 10, copyright);
    } else {
      copyright.className = "copyright-menu-open"
    }
  });
},
关于JavaScript中的范围和上下文的

Here's a useful article