【问题标题】:Referencing an object with through methods, events, and whatnot通过方法、事件等引用对象
【发布时间】:2011-04-25 08:57:17
【问题描述】:

设置

我正在尝试为我的网站制作一个基于对象的验证代码,您可以在其中将输入定义为对象并将属性附加到它,有点像这样

function input(id,isRequired) {
   this.id = id
   this.isRequired = isRequired
   this.getElement = getElem;
   this.getValue = getValue;
   this.writeSpan = writeSpan;
   this.checkText = checkText;
   this.isText = true
   this.checkEmpty = checkEmpty;
   this.isEmpty = true
   this.isValid = false
}

我目前有一个像这样设置的事件处理程序

firstName.getElement().onblur = function() {validate(firstName)}

其中 firstName 是输入对象,getElement() 方法执行以下操作:

function getElem() {
    return document.getElementById(this.id)
}

问题

我想要做的是能够通过使用类似于.this 的东西来使用 validate 函数引用 firstName 对象,并有效地删除匿名函数。我想这样做主要是因为我正在与不太熟悉 javascript 的团队成员一起工作,并且代码越少越好。

我猜我正在寻找的代码看起来像这样:

firstName.getElement().onblur = validate

function validate() {
    object = "your code here"
}

这可能吗?

【问题讨论】:

    标签: javascript events validation object


    【解决方案1】:

    看看.bind():

    firstName.getElement().onblur = validate.bind(firstName);
    

    这将使validate 函数内的this 引用firstName(因此它不会作为参数传递)。

    并非所有浏览器都支持它(它是 ECMAScript5 的一部分),但该链接显示了自定义实现。

    或者,您可以创建一个为您生成匿名函数的新函数:

    firstName.getElement().onblur = get_validator(firstName);
    

    get_validator 在哪里:

    function get_validator(obj) {
       return function() {
           validate(obj);
       }
    }
    

    或者你可以做同样的事情,但是作为input对象的一个​​方法,这样你只需要这样做:

    firstName.getElement().onblur = firstName.getValidator();
    

    【讨论】:

    • 感谢您的回复 :D 我认为这个答案和问题 + 一些!
    猜你喜欢
    • 2012-05-20
    • 2011-12-29
    • 1970-01-01
    • 2011-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-19
    • 1970-01-01
    相关资源
    最近更新 更多