Javascript Assigning.onmousedown with()在分配时运行函数,解决方法如下

Javascript Assigning.onmousedown with()在分配时运行函数,解决方法如下,javascript,Javascript,如果我这样做: image[i].onmousedown = whatever; image[i].onmousedown = whatever( name, what, when, where, how ); 它可以很好地工作,并在单击时运行whatever()函数。但是,如果我执行以下操作: image[i].onmousedown = whatever; image[i].onmousedown = whatever( name, what, when, where, how );

如果我这样做:

image[i].onmousedown = whatever;
image[i].onmousedown = whatever( name, what, when, where, how );
它可以很好地工作,并在单击时运行whatever()函数。但是,如果我执行以下操作:

image[i].onmousedown = 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 );
}

我还必须为“this”指定一个新值,看起来是这样吗?你们有什么建议,或者请告诉我你们有更好的方法。提前感谢您的帮助

您可以使用ECMAScript 5函数绑定上下文并设置要传入的参数

image[i].onmousedown = whatever.bind(this, name, what, when, where, how );  
这里是您绑定事件的当前上下文。如果要获取元素本身的上下文,请执行以下操作:

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

anotherwhater.call(这个、名字、什么、何时、何地、如何)再次你好,我的35k代表朋友!:]感谢您的回复,brb正在研究.call语法@Musa不需要调用,需要使用bind。调用将立即调用它。因此,
image[i].onmousedown=anotherwhater.bind(this,name,what,when,where,how)
.bind()
.call()
之间有很大的区别,一个函数返回另一个函数,就像是你函数的代理,而另一个函数则立即调用你的函数。如果要将结果直接分配给
.onmousedown
,请使用
.bind()
——它将返回一个具有正确
this
和其他参数的函数。使用
.call()
如果你想做
其他任何事()
它会用正确的
this
和其他参数立即调用另一个函数,如果它们都将被分配本质上相同的功能,这似乎是事件委派的一个很好的例子。如ECMAScript 5所述,请注意,
bind
仅在现代浏览器中可用……如果加载了jQuery,则可以使用
jQuery.proxy
;或者,您可以使用垫片,例如:嘿,谢谢您的帮助。我正要问你这个问题,因为结果是整个图像的“数组”或图像的所有值,而不是实际的“this”。但我还没来得及问你,你就回答了。我试过你的东西,但我认为它不起作用,它也没有,因为给值图像[I]点击时会返回什么值?你知道我怎么知道我点击的那个号码吗?还是有更好的方法。再次感谢你的帮助+1@HateNames当然可以。你能准备一把小提琴吗?我想当我准备小提琴的时候,我可能已经弄明白了,所以我会继续用它,你们给了我足够的时间继续,非常感谢你们的帮助!这种方法是有效的,唯一的问题是它不带“这个”。所以我必须做image[I].onmousedown=function(){which(this,name,what,when,where,how);};相反+对不起,我错了。编辑以修复此问题。