JS中的this指向問題()
-
在全域作用域中
=>this -> window
<script> console.log(this); //this->window </script> -
在普通函式中
=>this取決于誰呼叫,誰呼叫我,this就指向誰,跟如何定義無關
var obj = { fn1:function() { console.log(this); }, fn2:function(){ fn3() } } function fn3() { console.log(this); } fn3();//this->window obj.fn1();//this->obj obj.fn2();//this->window -
箭頭函式中的this
箭頭函式沒有自己的this,箭頭函式的this就是背景關系中定義的this,因為箭頭函式沒有自己的this所以不能用做建構式,
var div = document.querySelector('div'); var o={ a:function(){ var arr=[1]; //就是定義所在物件中的this //這里的this—>o arr.forEach(item=>{ //所以this -> o console.log(this); }) }, //這里的this指向window o是定義在window中的物件 b:()=>{ console.log(this); }, c:function() { console.log(this); } } div.addEventListener('click',item=>{ console.log(this);//this->window 這里的this就是定義上文window環境中的this }); o.a(); //this->o o.b();//this->window o.c();//this->o 普通函式誰呼叫就指向誰 -
事件系結中的this
事件源.onclik = function(){ } //this -> 事件源
事件源.addEventListener(function(){ }) //this->事件源
var div = document.querySelector('div'); div.addEventListener('click',function() { console.log(this); //this->div }); div.onclick = function() { console.log(this) //this->div } -
定時器中的this
定時器中的this->window,因為定時器中采用回呼函式作為處理函式,而回呼函式的this->window
setInterval(function() { console.log(this); //this->window },500) setTimeout(function() { console.log(this); //this->window },500) -
建構式中的this
建構式配合new使用, 而new關鍵字會將建構式中的this指向實體化物件,所以建構式中的this->實體化物件
new關鍵字會在內部發生什么
//第一行,創建一個空物件obj, var obj ={}; //第二行,將這個空物件的__proto__成員指向了建構式物件的prototype成員物件. obj.__proto__ = CO.prototype; //第三行,將建構式的作用域賦給新物件,因此CA函式中的this指向新物件obj,然后再呼叫CO函式,于是我們就給obj物件賦值了一個成員變數p,這個成員變數的值是” I’min constructed object”, CO.call(obj); //第四行,回傳新物件obj, return obj;function Person(name,age) { this.name = name; this.age = age; } var person1 = new Person(); person1.name = 'andy'; person1.age = 18; console.log(person1);//Person {name: "andy", age: 18} var person2 = new Person(); person2.name = 'huni'; person2.age = 20; console.log(person2);// Person {name: "huni", age: 20
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/190698.html
標籤:java
下一篇:【SaaS-Export專案】 - 04 前臺AdminLTE介紹與入門使用,AdminLTE漢化版下載,搭建一個AdminLTE入門頁面
