美文网首页
js之函数中的this指向

js之函数中的this指向

作者: 小黄鱼的偏执 | 来源:发表于2017-12-29 10:17 被阅读0次
    1. 普通模式调用函数,函数中的this是window。
    function a(){
        var user = "b";
        console.log(this); //Window
    }
    a();
    
    1. 如果是通过new的方式,函数中的this就是当前的实例对象。
    function Fn(){
        this.user = "张三";
    }
    var a = new Fn();
    console.log(a.user); //张三
    
    1. 对象中的方法,里面的this还是当前实例对象。
    var o = {
          user: "李四",
          fn: function () {
                console.log(this.user);//李四
          }
    }
    o.fn();
    
    1. 全局函数apply和call可以用来改变this的指向
    var fun = function(str) {
     this.status = str;
    }
    fun.prototype.getStatus = function() {
     alert(this.status);
    }
    var obj = {
     status: "loading"
    };
    fun.prototype.getStatus.apply(obj); // 输出"loading", 此时getStatus方法中的this指向了obj
    

    补充一点:在严格模式(use strict;)中的默认的this不再是window,而是undefined。

    相关文章

      网友评论

          本文标题:js之函数中的this指向

          本文链接:https://www.haomeiwen.com/subject/lhhbgxtx.html