zoukankan      html  css  js  c++  java
  • js中的this指向

        this 通常指向调用者,即谁调用指向谁。

    场景1:

            var a = 2;
            function fn() {
                console.log(this.a);
            }
            var obj = {
                a:123,
                fn:fn
            }
            fn(); // 2  this指向window
            obj.fn(); // 123 this指向obj

    场景2:appy 与call 可改变this 指向(call与apply的第一个参数是this指向)

            var a = 2;
            function fn() {
                console.log(this.a);
            }
            var obj = {
                a:123,
                fn:fn
            }
            fn(); // 2  this指向window
            fn.call(obj); // 123 this指向obj
            fn.call(window); // 2  this指向window

    场景3:箭头函数可以改变this指向,它的this绑定取决于外层

            var a = 2;
            var fn = () => {
                console.log(this.a);
            }
            var obj = {
                a:123,
                fn:fn
            }
            fn(); // 2  this指向window
            obj.fn(); // 2 this指向window 而不是obj

    场景4:事件中this指向事件对象元素

            var ul = document.getElementById("myul")
            ul.addEventListener('click', function () {
                console.log(this) // this 指向 id 为 myul 的标签
            })
  • 相关阅读:
    类的加载过程
    ASCII码表
    uboot main_loop函数分析
    串行CPU设计
    __attribute__ ((section(".text")))的测试
    NandFlash
    测试gcc的优化选项
    如何编写一个简单的makefile
    UBOOT的多支持性与可裁剪性
    函数指针的使用
  • 原文地址:https://www.cnblogs.com/jlyuan/p/11939312.html
Copyright © 2011-2022 走看看