| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
package org.mozilla.javascript; |
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
public class BoundFunction extends BaseFunction { |
| 15 |
|
| 16 |
static final long serialVersionUID = 2118137342826470729L; |
| 17 |
|
| 18 |
private final Callable targetFunction; |
| 19 |
private final Scriptable boundThis; |
| 20 |
private final Object[] boundArgs; |
| 21 |
private final int length; |
| 22 |
|
| 23 |
public BoundFunction(Context cx, Scriptable scope, Callable targetFunction, Scriptable boundThis, |
| 24 |
Object[] boundArgs) |
| 25 |
{ |
| 26 |
this.targetFunction = targetFunction; |
| 27 |
this.boundThis = boundThis; |
| 28 |
this.boundArgs = boundArgs; |
| 29 |
if (targetFunction instanceof BaseFunction) { |
| 30 |
length = Math.max(0, ((BaseFunction) targetFunction).getLength() - boundArgs.length); |
| 31 |
} else { |
| 32 |
length = 0; |
| 33 |
} |
| 34 |
|
| 35 |
ScriptRuntime.setFunctionProtoAndParent(this, scope); |
| 36 |
|
| 37 |
Function thrower = ScriptRuntime.typeErrorThrower(cx); |
| 38 |
NativeObject throwing = new NativeObject(); |
| 39 |
throwing.put("get", throwing, thrower); |
| 40 |
throwing.put("set", throwing, thrower); |
| 41 |
throwing.put("enumerable", throwing, false); |
| 42 |
throwing.put("configurable", throwing, false); |
| 43 |
throwing.preventExtensions(); |
| 44 |
|
| 45 |
this.defineOwnProperty(cx, "caller", throwing, false); |
| 46 |
this.defineOwnProperty(cx, "arguments", throwing, false); |
| 47 |
} |
| 48 |
|
| 49 |
@Override |
| 50 |
public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] extraArgs) |
| 51 |
{ |
| 52 |
Scriptable callThis = boundThis != null ? boundThis : ScriptRuntime.getTopCallScope(cx); |
| 53 |
return targetFunction.call(cx, scope, callThis, concat(boundArgs, extraArgs)); |
| 54 |
} |
| 55 |
|
| 56 |
@Override |
| 57 |
public Scriptable construct(Context cx, Scriptable scope, Object[] extraArgs) { |
| 58 |
if (targetFunction instanceof Function) { |
| 59 |
return ((Function) targetFunction).construct(cx, scope, concat(boundArgs, extraArgs)); |
| 60 |
} |
| 61 |
throw ScriptRuntime.typeError0("msg.not.ctor"); |
| 62 |
} |
| 63 |
|
| 64 |
@Override |
| 65 |
public boolean hasInstance(Scriptable instance) { |
| 66 |
if (targetFunction instanceof Function) { |
| 67 |
return ((Function) targetFunction).hasInstance(instance); |
| 68 |
} |
| 69 |
throw ScriptRuntime.typeError0("msg.not.ctor"); |
| 70 |
} |
| 71 |
|
| 72 |
@Override |
| 73 |
public int getLength() { |
| 74 |
return length; |
| 75 |
} |
| 76 |
|
| 77 |
private Object[] concat(Object[] first, Object[] second) { |
| 78 |
Object[] args = new Object[first.length + second.length]; |
| 79 |
System.arraycopy(first, 0, args, 0, first.length); |
| 80 |
System.arraycopy(second, 0, args, first.length, second.length); |
| 81 |
return args; |
| 82 |
} |
| 83 |
} |