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

标签 javascript

如果我在绑定(bind)到事件时不使用绑定(bind),我知道“this”指的是调用对象。如果我使用bind,那么我可以使“this”反射(reflect)该方法所在的类。现在我的问题是,如果我使用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)); 

我希望这个问题有意义,因为我的脑子里充斥着所有“这个”引用。

最佳答案

使用事件数据

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

这是一种将对象绑定(bind)到事件并仍然跟踪元素的方法。 fiddle :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

fiddle :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")

关于Javascript Function.prototype.bind 这是这个/如何找到这个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23611465/

相关文章:

javascript - 如何使用 javascript 删除 tile(metro ui css) 的缩放效果

javascript - 未声明 JS 命名空间 Netbeans 变量

javascript - 安全覆盖 Google Chrome 扩展中的 document.cookie

javascript - 获取 Cosmos DB 中的文档大小

javascript - 如何从 Jqwidgets 中的嵌套行获取选定行数据

javascript - 使用每个选择的值填充 jquery 数组

javascript - 不使用 jquery animate() 动画元素

javascript - Protractor 未检测到弹出对话框(md-dialog-content)

javascript - 如何使用 JAVASCRIPT/正则表达式从字符串中找到 "&lt;script&gt;"标签

javascript - 为什么 javascript 在具有共享/部分 View 的 asp.net mvc View 中不起作用