簡體   English   中英

這是Javascript Function.prototype.bind /如何找到此

[英]Javascript Function.prototype.bind which this is this / how to find this

如果在綁定到事件時不使用綁定,那么我知道“ this”是指調用對象。 如果使用bind,則可以使“ this”反映該方法所在的類。現在我的問題是,如果我使用bind,則“ this”指向該方法所在的類,是否可以引用該方法?現在“ this”正在引用該類的調用對象?

例如:

//inside me.handleClick "this" will refer to obj
obj.attachEvent("onclick", this.handleClick); 

//inside this.handleClick "this" will refer to the object that handleClick is a member of. how do I get a reference to obj inside handleClick?
obj.attachEvent("onclick", this.handleClick.bind(this)); 

我希望這個問題是有道理的,因為我對所有“ this”參考文獻都感到困惑。

使用事件數據

當您將事件處理程序添加到元素時,javascript將事件對象作為參數傳遞給該函數。 在此對象中,有一個名為toElement屬性,該屬性存儲了調用此事件的元素。

這是一種將對象綁定到事件並保持對元素的跟蹤的方法。 小提琴: http//jsfiddle.net/QZXhL/1/

JS

//The constructor
var Button = function(selector) {
    this.element = document.querySelector(selector)
    //Bind both events
    this.element.addEventListener("click", this.handler1)
    this.element.addEventListener("click", this.handler2.bind(this))
}

Button.prototype.handler1 = function() {
    console.log("Handler 1")
    console.log(this) //Should be <button>
}

Button.prototype.handler2 = function(e) {
    console.log("Handler 2")
    console.log(this) //Will be the button object in js
    console.log(e.currentTarget) //will be the <button> element
}

var button = new Button("button")

您可以使用特殊功能handleEvent MDN文檔來進一步清理此代碼: https : //developer.mozilla.org/zh-CN/docs/Web/API/EventTarget.addEventListener#The_value_of_this_within_the_handler

小提琴: http : //jsfiddle.net/QZXhL/2/

var Button = function(selector) {
    this.element = document.querySelector(selector)
    this.element.addEventListener("click", this)
}

Button.prototype.handleEvent = function(e) {
    console.log("Using handleEvent")
    console.log(this)
    console.log(e.currentTarget) 
}

var button = new Button("button")

我會做這樣的事情:

var that = this;
obj.attachEvent("onclick", function() {
    that.handleClick(this);
});
  • 您不能直接在對象上調用方法,因為this始終引用事件中的DOM元素。 這就是為什么您需要匿名函數的原因。
  • 因為您不在同一上下文中that所以需要創建另一個對對象的引用(請記住:在匿名函數內部, this是指DOM元素obj )。

之后,在handleClickthis將引用您的自定義對象,而傳遞給該方法的第一個參數將是obj (即DOM元素)。

請注意, attachEvent特定於Internet Explorer。 您必須使用addEventListener才能與所有瀏覽器一起使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM