QUnit.test("jQuery.proxy", function(assert) {
\t assert.expect(9);
\t var test2, test3, test4, fn, cb,
\t \t test = function() {
\t \t \t assert.equal(this, thisObject, "Make sure that scope is set properly.");
\t \t },
\t \t thisObject = { foo: "bar", method: test };
\t // Make sure normal works
\t test.call(thisObject);
\t // Basic scoping
\t jQuery.proxy(test, thisObject)();
\t // Another take on it
\t jQuery.proxy(thisObject, "method")();
\t // Make sure it doesn't freak out
\t assert.equal(jQuery.proxy(null, thisObject), undefined, "Make sure no function was returned.");
\t // Partial application
\t test2 = function(a) {
\t \t assert.equal(a, "pre-applied", "Ensure arguments can be pre-applied.");
\t };
\t jQuery.proxy(test2, null, "pre-applied")();
\t // Partial application w/ normal arguments
\t test3 = function(a, b) {
\t \t assert.equal(b, "normal", "Ensure arguments can be pre-applied and passed as usual.");
\t };
\t jQuery.proxy(test3, null, "pre-applied")("normal");
\t // Test old syntax
\t test4 = { "meth": function(a) {
\t \t assert.equal(a, "boom", "Ensure old syntax works.");
\t } };
\t jQuery.proxy(test4, "meth")("boom");
\t // jQuery 1.9 improved currying with `this` object
\t fn = function() {
\t \t assert.equal(Array.prototype.join.call(arguments, ","), "arg1,arg2,arg3", "args passed");
\t \t assert.equal(this.foo, "bar", "this-object passed");
\t };
\t cb = jQuery.proxy(fn, null, "arg1", "arg2");
\t cb.call(thisObject, "arg3");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/qunit/qunit-2.4.0.css">
<script src="https://code.jquery.com/qunit/qunit-2.4.0.js"></script>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/ – null1941
一般在jQuery的你不參考或咖喱,你做更像'$ .fn.marginBoxHeight = function(){return this.outerHeight(true); }' – adeneo
謝謝@adeneo是的,我知道,事實上,這就是我解決問題的方式 - 這更像是一個學術問題。我得看看源代碼;我猜測正確的範圍可能是'$ .fn.init'或'$ .fn.init.prototype' – lunelson