首頁  >  文章  >  web前端  >  js中this的指向問題探討

js中this的指向問題探討

小云云
小云云原創
2018-03-16 17:09:091214瀏覽

本文主要和大家分享js中this的指向問題探討,this關鍵字代表目前正在執行的方法的對象,如果沒有當前方法,則是指全域變數。就是說this代表呼叫該方法的物件的參考。

一、全域作用域或在普通函數中this指向全域物件window。

//直接打印
    console.log(this) //window
//function声明函数
    function bar () {conso
le.log(this)}bar() //window
//function声明函数赋给变量
    var bar = function () {console.log(this)}bar() //window
//自执行函数
    (function () {console.log(this)})(); //window

#二、方法呼叫中誰呼叫this指向誰

//对象方法调用
    var person = {run: function () {console.log(this)}}person.run()// person
//事件绑定
    var btn = document.querySelector("button")btn.onclick = function () {console.log(this) // btn}
//事件监听
    var btn = document.querySelector("button")btn.addEventListener('click', function () {console.log(this) //btn})
//jquery的ajax
    $.ajax({ self: this,    type:"get",    url: url,    async:true,    success: function (res) {console.log(this)
 // this指向传入$.ajxa()中的对象
    console.log(self) // window  } }); 
//这里说明以下,将代码简写为$.ajax(obj) ,this指向obj,在obj中this指向window,因为在在success方法中,独享obj调用自己,所以this指向obj

#三、#在建構函式或建構子原型物件中this指向建構子的實例

//不使用new指向window
    windowfunction Person (name) {console.log(this) // window    
    this.name = name;}Person('inwe')
//使用new
    function Person (name) {this.name = name   console.log(this) //people     
    self = this  }  var people = new Person('iwen')  console.log(self === people) //true
//这里new改变了this指向,将this由window指向Person的实例对象people
new改变this指向,将this指向window改为指向person的实例people

改變this的指向:

    函數本身就是一個特殊類型,大多數認為是一個變量,this指向誰在函數定義時候確定不了,只有在函數執行時候才可以確定this到底指向誰,實際上this指向的是最終調用他的函數。

相關推薦:

PHP中$this的用法與存取限定符詳解

修改JavaScript中的this指向的多種方法

JavaScript中的this規則及this物件用法實例

#

以上是js中this的指向問題探討的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn