【发布时间】:2018-09-22 07:27:11
【问题描述】:
我也想吃蛋糕:我想有一个方法,它在绑定到对象时返回this 用于链接,但在使用空|未定义范围调用时返回undefined。这似乎工作正常,但如果你把它放入JSLint,那么你会得到一个严格的违规错误。我不需要使用严格模式,但似乎这应该是可能的和it works(打开控制台)。这可以吗和/或您还可以如何实现这种效果?
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;
}());
如果你查看控制台:
var localM = o.meth; // now scopeless
console.log( o.meth('key', 'val') ); // should return `o`
console.log( localM('key', 'val') ); // should return `undefined`
【问题讨论】:
-
有人说 undefined 不应该以这种方式进行比较(== 或 ===),因为它可以在您或第三方代码的某处重新定义。这样做当然是个坏习惯。
-
@PiotrSalaciak 是的,为了这个问题,我假设环境干净。我刚刚添加了
undefinedtho 作为你的第一个参数(这将是=== undefinedb/c 它是用零参数调用的;)另一种安全的方法是比较=== void 0。
标签: javascript this ecmascript-5 strict-mode