用()赋值.onmousedown时,函数会在赋值时运行

Assigning .onmousedown with () runs the function when assigned , work arounds

本文关键字:赋值 运行 函数 onmousedown      更新时间:2023-09-26

如果我这样做:

image[i].onmousedown = whatever;

它将工作得很好,并在点击时运行whatever()函数。但是,如果我做以下操作:

image[i].onmousedown = whatever( name, what, when, where, how );

赋值属性时会运行函数。假设我创建了30张图片并想给它们所有的onmousedown函数,它会在加载时运行这个函数30次因为我在后面添加了()但是我要怎么给函数分配我想要的属性呢?

是使函数运行函数的唯一方法吗?所以输入

image[i].onmousedown = whatever;
function whatever() {
   anotherWhatever( this, name, what, when, where, how );
}

我还必须分配一个新的值'这个'似乎?你们有什么建议或者请告诉我你们有更好的方法。提前感谢您的帮助

您可以使用ecmaScript5 bind函数来绑定上下文并设置要传入的参数。

image[i].onmousedown = whatever.bind(this, name, what, when, where, how );  
这里的

this将是绑定事件的当前上下文。如果你想获得元素本身的上下文,那么:

image[i].onmousedown = whatever.bind(image[i], name, what, when, where, how );  

如MDN中所述,您可以将此脚本放在您的js中以获得旧浏览器的支持。

if (!Function.prototype.bind) {
  Function.prototype.bind = function (oThis) {
    if (typeof this !== "function") {
      // closest thing possible to the ECMAScript 5 internal IsCallable function
      throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
    }
    var aArgs = Array.prototype.slice.call(arguments, 1), 
        fToBind = this, 
        fNOP = function () {},
        fBound = function () {
          return fToBind.apply(this instanceof fNOP && oThis
                                 ? this
                                 : oThis,
                               aArgs.concat(Array.prototype.slice.call(arguments)));
        };
    fNOP.prototype = this.prototype;
    fBound.prototype = new fNOP();
    return fBound;
  };
}

您需要将其封装在一个匿名函数中:

image[i].onmousedown = function () { whatever.call(this, name, what, when, where, how ); };