haozy123 2017-07-20 03:57 采纳率: 0%
浏览 1452

onload中变量赋值,作用域链解答

onload = function () {
var current;
var rows = document.getElementById("tbl").getElementsByTagName("tr");
for (var i = 1; i < rows.length; i++) {
rows[i].onclick = function () {
if (current) current.style.backgroundColor = "";
this.style.backgroundColor = "pink";
current = this;
};

            rows[i].onmouseover = function () {
                // 如果进入的这一行是点过的那一行,就不管
                if (current === this) return;
                this.style.backgroundColor = "#cccccc";
            };

            rows[i].onmouseout = function () {
                // 如果离开的这一行是点过的那一行,就不管
                if (current === this) return;
                this.style.backgroundColor = "";

            };
        }


    };
            问:为什么onload的current可以得到this值,请用作用域链的相关知识解答
  • 写回答

1条回答 默认 最新

  • I1326 2017-07-20 05:56
    关注

    函数注册时会自动填充一个全局对象,包括this,对于直接定义的函数,this指向window;var current=this也就时俗称保存this,这时候的this作用域默认状态下是它的定义处的作用域链。(当函数被调用的时候会拥有一个“运行期上下文”的内部对象,这玩意又有自己的作用域链,当他被创建的时候初始化为当前运行函数的所包含的对象,共同组成一个活动对象)
    大致是i这个意思,说的可能不是很清除你自己打印一下看的就很清楚了,如果还是不理解就翻翻作用域与this指向部分文档吧

     onload = function () {
                var current;
                console.log("直接定义this->"+this);
                var libox = document.getElementById("tbl").getElementsByTagName("li");
                for (var i = 1; i < libox.length; i++) {
                    console.log("for循环内的this->"+this);
                    libox[i].onclick = function () {
                    if (current) current.style.backgroundColor = "";
                        this.style.backgroundColor = "pink";
                        current = this;
                        console.log("if内部的this->"+this);
                    };
                    libox[i].onmouseover = function () {
                        console.log("mouseover事件->"+this);
                        // 如果进入的这一行是点过的那一行,就不管
                        if (current === this) return;
                        this.style.backgroundColor = "#cccccc";
                    };
                    libox[i].onmouseout = function () {
                        console.log("mouseout事件->"+this);
                        // 如果离开的这一行是点过的那一行,就不管
                        if (current === this) return;
                        this.style.backgroundColor = "";
                    };
                }
            };
    
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器