Javascript Function.prototype.bind这是这个/如何找到这个

时间:2014-05-12 14:16:08

标签: javascript

如果我在绑定事件时没有使用bind,我知道"这个"指的是调用对象。如果我使用bind,那么我可以制作"这个"反映了该方法所存在的类。现在我的问题是,如果我使用bind,那么"这个"指的是该方法所在的类是否有一种方法来引用调用对象现在"这个"正在引用该类?

例如:

//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)); 

我希望这个问题有道理,因为我的头脑旋转着所有的"这个"引用。

2 个答案:

答案 0 :(得分:1)

使用事件数据

当您向元素添加事件处理程序时,javascript会将事件对象作为参数传递给该函数。在这个对象中有一个名为toElement的proeprty,它存储调用此事件的元素。

这是一种将对象绑定到事件并仍然跟踪元素的方法。 小提琴: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/en-US/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")

答案 1 :(得分:0)

我会做这样的事情:

var that = this;
obj.attachEvent("onclick", function() {
    that.handleClick(this);
});
  • 您无法直接调用对象上的方法,因为this始终引用事件中的DOM元素。这就是你需要匿名功能的原因。
  • that需要创建对象的另一个引用,因为您不在同一个上下文中(请记住:在匿名函数内,this引用DOM元素{{1} })。

之后,在obj中,handleClick将引用您的自定义对象,而传递给该方法的第一个参数将是this(例如DOM元素)。

请注意,obj特定于Internet Explorer。您必须使用attachEvent才能使用所有浏览器。

相关问题