简体   繁体   English

如何将原型函数映射到具有该原型的对象数组?

[英]How can I map a prototype function to an array of objects that have that prototype?

Is there a way in javascript to get a handle on a object prototype function with the this guaranteed to be the object in question? 在javascript中,有没有一种方法可以保证对象原型函数得到处理? I particularly got to a PITA situation when I wanted to map an array of objects of the proper type to such a function. 当我想将适当类型的对象数组映射到此类函数时,我特别遇到了PITA的情况。 This ended up being Window. 最终成为Window。 Yes I did pull the function itself from the proper place but internally it refers to 'this'. 是的,我确实从适当的地方提取了函数本身,但在内部它是指“ this”。 I know about call and apply but not how you might use them to handle this sort of situation. 我了解电话申请的知识,但不知道如何使用它们来处理这种情况。

Is there a way short of an explicit loop instead of using map? 有没有一种方法可以使用显式循环而不使用map? Oddly it apparently does not do the same thing re 'this' as 奇怪的是,它显然不像“ this”那样做相同的事情

object_with_the_prototype.some_prototype_function() 

would do if instead I have 如果我有的话会做

[object_with_the_prototype].map(this.some_prototype_function)

How come? 怎么会?

if your method expects one argument, then it's easy. 如果您的方法需要一个参数,那么这很容易。 If you need more than one argument, or more importantly, not a number as a 2nd argument (think .toString), then you can use bind to curry this into the 1st argument: 如果您需要多个参数,或者更重要的是,不需要数字作为第二个参数(请考虑.toString),则可以使用bind将其作为第一个参数:

"a,b,c".split(",").map( Function.call.bind(  "".big  )  );

in your code: 在您的代码中:

[object_with_the_prototype]
  .map( Function.call.bind( thisObject.some_prototype_function ) );

if your method calls like x(a,b,c), the bound function calls like x(this, a, b, c) 如果您的方法像x(a,b,c)那样调用,则绑定函数像x(this,a,b,c)那样调用

I think you are looking for this: 我认为您正在寻找:

[object_with_the_prototype].map(function(thisObject) {
    thisObject.some_prototype_function();
} );

Ah, I see it. 嗯,我明白了。 The problem is that in the array case I was mistakenly assuming that the normal walk from the object up its prototype chain would happen although I was giving it an explicit function to map to. 问题是,在数组的情况下,我错误地假设了从对象到其原型链的正常移动会发生,尽管我为它提供了一个明确的函数来映射。 I fixed it by defining a function taking an element from the array and calling the desired prototype function through that element. 我通过定义一个从数组中获取元素并通过该元素调用所需原型函数的函数来修复该问题。 I map to that function instead. 我改为映射到该函数。

function do_one(element) {element.some_prototype_function()}
[object_with_prototype].map(do_one)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM