JavaScript中的this关键字

作者: 07120665a058 | 来源:发表于2017-03-07 14:01 被阅读24次

JavaScript的函数中,除了函数声明时定义的形参之外,每个函数还可以接收另一个隐藏的参数this,又称this引用。

一、 this的指向

this的值(即它的指向)取决于调用的方式。在javascript中this指向大致有以下四种情况:
  • 1.无任何前缀的函数调用时,this指向顶层对象或者叫全局对象,浏览器里是windownodejs里是global
function fn(){
        console.log(this);
}
fn();                //输出window{...}
  • 2.方法调用的时候,this指向方法所在的对象
let fn={
          name:"huanglizhen",
          say:function(){
               console.log("my name is "+this.name);
          }
}
fn.say();      //输出 "my name is huanglizhen"
  • 3.构造函数里,this指向新生成的实例
function Fn(name){
        this.name=name;
        this.say=function(){
           console.log("my name is "+this.name);
        }
}
let fn1=new Fn("huanglizhen");
fn1.say();                    // 输出为 "my name is huanglizhen"
let fn2=new fn("Lily");      // 输出为 "my name is Lily"
fn2.say();
  • 4.apply/call调用的时候,this指向apply/call方法中的第一个参数
let robot_1 = {name:'cup'}
let robot_2 = {name:'bower'}
function say(){
      console.log(this.name)
}
say.call(robot_1)     //  打印结果为'cup'
say.call(robot_2)     //  打印结果为'bower'

二、浏览器和Node里的this对比

  • 在浏览器里面this等价于window对象,不管在任何地方声明的全局变量都会作为 this的属性
  • 在node里面this不一定等价于global对象
    • 如果直接执行写好的JS文件,声明的全局变量会自动添加给global,不会自动添加到this
    • 如果直接在里面执行一行行代码,声明的全局变量会自动添加给global,顺带也会添加给this
  • 创建变量时没带varlet关键字,会赋值给全局的global但不是this

三、demo about what can change points to this

foo = "bar";
function testThis() {
  this.foo = "foo";
}
console.log(this.foo);                // "bar"
console.log(new testThis());          //[object Object]{foo:"foo"}不会改变指向
console.log(this.foo);                // "bar"
  
console.log(testThis());              //undefined 调用testThis()就会改变指向
console.log(this.foo);                // "foo"            

console.log(new testThis().foo);      // "foo"
<script type="text/javascript">
    foo = "bar";
    function testThis() {
      "use strict";
      this.foo = "foo";
    }
  
    console.log(this.foo);    //"bar"
    console.log(testThis());  
   //Uncaught TypeError: Cannot set property 'foo' of undefined 
   //严格模式下会报错,非严格模式为undefined
  </script>

相关文章推荐:
JavaScript中的this
JavaScript中的this陷阱的最全收集

相关文章

网友评论

本文标题:JavaScript中的this关键字

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