I want to have my cake and eat it too: I want to have a method that returns this
for chaining when it is bound to an object but returns undefined
when it is called with a null|undefined scope. This seems to work fine but if you put it into JSLint then you get a Strict Violation errors. I don't need to use strict mode, but it seems like this should be possible and it works (open the console). Is this okay and/or how else could you accomplish this effect?
var o = {}; // or some pre-existing module
o.meth = (function (undefined) {
// contrived example where you'd want to be able to locally
// access `meth` even if the outer `o.meth` was overwritten
'use strict';
var hash = Object.create(null); // "object" with no properties
// global ref - or `null` where strict mode works
var cantTouchThis = (function () {
return this;
}).call(null);
function meth (k, v) {
var n;
if (typeof k == 'object') { // set multi
for (n in k) {
meth(n, k[n]);
}
} else {
if (v === undefined) { return hash[k]; } // get
hash[k] = v; // set
}
if (this == cantTouchThis) { return; }
return this;
}
return meth;
}());
And if you look in the console:
var localM = o.meth; // now scopeless
console.log( o.meth('key', 'val') ); // should return `o`
console.log( localM('key', 'val') ); // should return `undefined`