Examining Context

from jquery ninja book

by dandoyon

HTML

<ul id="results"></ul>

CSS

#results li.pass { color: green; }
#results li.fail { color: red; }

JavaScript

function assert(value, desc) {
    var li = document.createElement("li");
    li.className = value ? "pass" : "fail";
    li.appendChild(document.createTextNode(desc));
    document.getElementById("results").appendChild(li);
}


var katana = {
    isSharp: true,
    use: function() {
        this.isSharp = !this.isSharp;
    }
};
katana.use();
assert(!katana.isSharp, "The value of isSharp has been changed!");

function katanaGlobal() {
    this.isSharp = true;
}
assert(typeof isSharp === 'undefined', "A global property does not exists.");
katanaGlobal();
assert(isSharp === true, "A global property now exists.");


function fn() {
    return this;
}
var ronin = {};
assert(fn() == this, "The context is the global object.");
assert(fn.call(ronin) == ronin, "The context is changed to a specific object.");


function add(a, b) {
    return a + b;
}
assert(add.call(this, 1, 2) == 3, ".call() takes individual arguments");
assert(add.apply(this, [1, 2]) == 3, ".apply() takes an array of arguments");

assert(add.call(null, 1, 2) == 3, ".call() null context should work");
assert(add.apply(null, [1, 2]) == 3, ".apply() null context should work");