0
点赞
收藏
分享

微信扫一扫

JS篇 this指向问题

芭芭蘑菇 2022-04-21 阅读 68
javascript

注意:

例1.

       var name = 'Jay';
        function Person(name) {
            this.name = name
            console.log(this.name);
        }
        var a = Person('Tom')
        console.log(name);
        console.log(a);
        var b = new Person('Michael')
        console.log(b);

例2.

      var obj = {
            a: 1,
            b: function() {
                alert(this.a)
            }
        };
        var fun = obj.b; //相当于var fun = function(){alert(this.a)};
        fun(); //没有谁来调用的时候,this自然指向window
        //而window里面没有定义a,所以弹出undefined


      //类似题
       var user = {
            count: 1,
            getCount: function() {
                return this.count;
            }
        }
        var func = user.getCount  
        //等价于 var func=function(return this.count)
        // 所以this 指向window 
        //var func =user. getCount()表示调用方法 这个时候才输出1
        console.log(func())
     //输出undefined

例3.

function a(){
  console.log(this);
} 
a.call(null);

例4. 

 

例5. 


        var myObject = {
            foo: "bar",
            func: function() {
                var self = this;
                console.log(this.foo);
                console.log(self.foo);
                (function() {
                    console.log(this.foo);
                    console.log(self.foo);
                }());
            }
        };
        myObject.func();//指向myObject对象
        // 输出 bar bar  undefined   bar

例6.

var color = 'green';
var test4399 = {
    color: 'blue',
    getColor: function(){
        var color = "red";
        alert(this.color);
    }
}
var getColor = test4399.getColor;
//相当于var getColor=function {
//var color='red';alert(this.color)}

getColor();//没有谁调用,指向window
test4399.getColor();//this 指向test4399这个对象
//弹出 green   blue

例7.

// 在JavaScript的函数中,this始终指向调用者的上下文环境
var len = 117 // 5. 全局作用域中使用 var 定义的变量默认会成为 window 的属性,及 window.len
let func = {
  len: 935,
  showLen: function () {
    console.log(this.len) // 4. this 此时指向的是 window,所以相当于打印 window.len
  },
  show: function () {
    (function (cb) {
      cb() // 3. cb 相当于 cb.call() 默认没有传入上下文环境时 this 指向全局的 window 对象
    })(this.showLen) // 2. this 是 func 所以传入的是上面定义的 showLen 函数
  }
}

func.show() // 1. 相当于 func.show.call(func),此时 this 是 func
//len输出117

例8.  假设document是HTML文档中的一个节点,点击该节点后会发生什么?//输出true

function test() {
  this.flag = false;
  this.change = () => {
    this.flag = true;
    console.log(button.flag);
  };
}
const button = new test();
document.addEventListener("click", button.change);

例9.  输出window

var obj = {};
obj.log = console.log;
obj.log.call(console,this);

 

举报

相关推荐

0 条评论