Example 1 — Lock this with Function + Context
Official pattern: keep this on your object, not the caller.
var you = {
type: "person",
test: function () {
return this.type;
}
};
var raw = you.test.call({ type: "element" });
var locked = $.proxy(you.test, you).call({ type: "element" });
console.log(raw); // "element"
console.log(locked); // "person"
How It Works
- Raw call.
.call({ type: "element" }) forces this to that object. - Proxy.
$.proxy(you.test, you) returns a wrapper that ignores the caller’s this. - Locked. Even with the same
.call(...), the wrapper still uses you.
Example 2 — Context + Method Name
Official second signature: look up the method by string name.
var obj = {
name: "John",
test: function () {
return this.name;
}
};
var handler = $.proxy(obj, "test");
console.log(handler()); // "John"
console.log(handler.call({ name: "X" })); // "John"
How It Works
- Lookup.
$.proxy(obj, "test") uses obj.test as the function. - Context. Calls always use
obj as this. - Stable. A second
.call with another object still prints "John".
Example 3 — Pre-fill Extra Arguments
Since jQuery 1.6, extra args are prepended before the normal call args.
var me = {
type: "dog",
test: function (one, two) {
return one.type + " / " + this.type + " / " + two.type;
}
};
var proxy = $.proxy(me.test, me, { type: "cat" }, { type: "fish" });
console.log(proxy()); // "cat / dog / fish"
How It Works
- Extra args.
cat and fish are baked into the proxy. - Order. They become
one and two before any later call arguments. - Context.
this.type is still "dog" from me.