zoukankan      html  css  js  c++  java
  • 理解JavaScript中的this

    一、this出现的几种情况

    1、构造函数中的this

    function Fn(){
    	console.log(this);	
    }
    var obj1 = new Fn(); //obj1, 函数Fn中的this指向实例对象obj1

    2、普通函数中的this

    function Fn1(){
    	console.log(this);	
    }
    Fn1(); //window, Fn1属于window全局对象的一个属性,即:Fn1()===window.Fn1(),函数Fn1中的this指向window对象
    Fn()===window.Fn(); //window, Fn属于window全局对象的一个属性,即:Fn()===window.Fn(),函数Fn中的this指向window对象
    

    3、对象中的this

    var obj = {
    	that: this,
    	fn: function(){
    		console.log(this);	
    	}
    }
    console.log(obj.that); //window, this不存在Object对象中的,this指向window全局对象
    obj.fn(); //obj, this指向调用其所在函数的对象

    二、总结:

    1、this不存在Object对象中的,它只存在一个Function类型的函数中

    2、this指向使用new操作符实例化其所在函数的实例对象

    3、this还指向调用其所在函数的对象

    三、误区:

    1、注意在全局函数中的this

    var obj = {
    	fn: function(){
    		function test(){
    			console.log(this);
    		}
    		test();
    	}
    }
    obj.fn(); //window, test属于window对象的属性,因此this指向的是window对象,而不是obj对象

    2、上面的例子中,this一般被误认为obj对象,其实不是的,它指向window全局对象,但可以通过obj中的一个局部变量来指向obj

    var obj = {
    	fn: function(){
    		var self = this;
    		function test(){
    			console.log(self); //用self来指向obj对象
    		}
    		test();
    	}
    }
    obj.fn(); //obj

    3、方法的赋值表达式 

    var obj = {
    	prototype: "value",
    	fn: function(){
    		var self = this;
    		function test(){
    			console.log(this.prototype); //undefined,this指向window对象
    			console.log(self.prototype); //value,用self来指向obj对象
    		}
    		test();
    	}
    }
    obj.fn();
    var fn = obj.fn;
    fn(); //输出两个undefined,this指向window对象, 上一句中变量fn是window对象的一个属性,此时的self变量保存的还是window对象
    

    综上:this总是指向其所在函数类型的对象以及调用其所在函数中的(顶层)对象.

  • 相关阅读:
    linux 彻底删除文件及 find命令permission refused问题解决
    ubuntu系统中dpkg lock问题分析及解决
    ubuntu server18.04 更换默认源为阿里源-加速
    docker安装与卸载( liunx )
    ubuntu下dpkg lock问题
    docker pull报x509问题及docker启动失败问题解决
    windows 常用命令行操作
    uwsgi运行django应用是报错no app loaded. going in full dynamic mode
    internal server error原因及解决
    docker-compose启动容器后执行脚本或命令不退出 | 运行内部程序
  • 原文地址:https://www.cnblogs.com/yangjunhua/p/2475361.html
Copyright © 2011-2022 走看看