Chapter 2 - method context

by Denise Nepraunig

HTML

<link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-1.14.0.css">
<script src="http://code.jquery.com/qunit/qunit-1.14.0.js"></script>
  <div id="qunit"></div>
  <div id="qunit-fixture"></div>

JavaScript

// Programming JavaScript Applications
// Chapter 2
// Method context

// take care when this function is invoked as function, without cutoff
// then this will pollute the global namespace
function highPass(number, cutoff) {
    cutoff = cutoff || this.cutoff;
    return (number >= cutoff);
}

var filter1 = {
        highPass: highPass,
        cutoff: 5
    },
    filter2 = {
        // no highpass here
        cutoff: 3
    };

QUnit.test("Invoking a function", function (assert) {
    expect(5);
    var result = highPass(6, 5);                    // function invokation    
    var result2 = highPass(5, 6);                   // -"-
    var result3 = filter1.highPass(3);              // method invokation
    var result4 = highPass.call(filter2, 3);        // call: call any method/function on any object
    var result5 = filter1.highPass(6);            
    
    assert.equal(result, true, "6 >= 5 should be true");
    assert.equal(result2, false, "5 >= 6 should be false");
    assert.equal(result3, false, "3 >= 5 should be false");
    assert.equal(result4, true, "3 >= 3 should be true");
    assert.equal(result5, true, "6 >= 6 should be true");
});



QUnit.test("Using apply test", function(assert) {
// apply is used for array like objects
    var numbers = [1,2,3,4,5];
    var maxNum = Math.max.apply(null, numbers);
    assert.equal(maxNum, 5, "the biggest number should be 5");
});