this关键字

this关键字,在不同对象中不同的值,它所取决于它使用的位置

  • 在方法中,this 指的是所有者对象。
  • 单独的情况下,this 指的是全局对象。
  • 在函数中,this 指的是全局对象。
  • 在函数中,严格模式下,this 是 undefined。
  • 在事件中,this 指的是接收事件的元素。

像 call() 和 apply() 这样的方法可以将 this 引用到任何对象。

1>、普通函数    谁调用就指向谁
function f1(){
       console.log(111);
       console.log(this);        
}
f1();
window.f1();
2>、对象里的方法 this是指当前的对象
var obj = {
            a: "111",
            b: "222",
            print: function() {
                console.log(11111);
                console.log(this);
            }
        }
3>、构造函数里面的this

        // function Student(name, age) {
        //     this.name = name;
        //     this.age = age;
        //     console.log(this);

        // }

        // (1) 把构造函数当成普通函数调用  this指向window
        // Student("张三", 18);

        // (2) 作为构造函数   this就指向new关键字创建的实例化对象
        // var s = new Student("张三", 16);
        // console.log(s);
        // console.log(s.name);  // "张三"
        // console.log(window.name); // ""


        // (3) 当做为构造函数时   返回值默认是new关键字创建的实例化对象  但是  如果手动添加了返回值 那么 如果是基本数据类型  就不会影响  如果是复杂数据类型 那么就会覆盖掉默认的返回值
        function Student(name, age) {
            this.name = name;
            this.age = age;
            console.log(this);

            // return {
            //     name : "1111",
            //     age : 1111
            // };

            return [12, 13, 15];
        }

        var s1 = new Student("丽丽", 16);
        console.log(s1.age);
4>、函数中调用是指全局对象
var a = 1;
function fn(){
  var a = 2;
  console.log(a);
}
fn(); //1

//所以要注意的是:
//在浏览器中:
fn() === window;

//在Node中:
fn() === global;
5>、严格模式下,this执行上下文时的值,不存在全局变量,所以this是undefined
"use strict"
function fn(a){
    console.log(this);
}
fn(1);   //undefined

fn() === undefined; // true
6>、当函数被用作事件处理函数时,谁触发的this指向谁
<input id="myinput" type="text" value="javascript中onclick中的this" onclick="javascript:test(this);"/>


function test(obj){
    alert(obj); //[object HTMLInputElement]
    alert(obj.id); //myinput
    alert(obj.value); //javascript中onclick中的this
}     
7>、在ES6里面   箭头函数的this指向  是继承自父级执行上下文中的this
        // 箭头函数没有自己的this, 他的this是从父级继承而来的  箭头函数的this在定义的时候就已经确定了  

var name = "我在window里面";

        // var obj = {
        //     name: "我是obj里面的",
        //     fn: () => {

        //         console.log(this);

        //         var that = this;

        //         setTimeout(() => {
        //             console.log(this.name);  // "我在window里面"
        //             console.log(that.name);  // "我在window里面" 
        //         }, 1000)

        //     }
        // }

        // obj.fn();
8>、// apply调用   改变函数的调用对象 第一个参数值就表示返回的值
        var x = 0; 
        function test(){
            alert(this.x);
        }
        var o = {};
        o.x = 1;
        o.m = test;
        o.m.apply();    //  0
总结  : 普通函数 : this是在调用的时候确定   谁调用  this就指向谁
            箭头函数 : this是在声明的时候就已经确定 而且不会改变   this是继承自父级执行上下文的this
原文地址:https://www.cnblogs.com/zycs/p/13306865.html