1. 程式人生 > 實用技巧 >this關鍵字

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