我也想吃蛋糕:我想有一个方法,当它绑定到对象时,它返回this进行链接,但是当它以null | undefined范围调用时,返回undefined。这似乎工作正常,但如果将其放入JSLint,则将出现“严重违反”错误。我不需要使用严格模式,但似乎应该可以使用it works(打开控制台)。可以吗?和/或还有其他方法可以达到这种效果?var o = {}; // or some pre-existing moduleo.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 scopelessconsole.log( o.meth('key', 'val') ); // should return `o`console.log( localM('key', 'val') ); // should return `undefined` 最佳答案 这几乎可以满足您的要求。在支持“使用严格”指令的环境中,dontTouchThis将是null,在不支持该指令的环境中将引用全局对象。首先,您可以仅用.call(null)替换该(function(){return this})()块;它或多或少会产生相同的效果。第二,当涉及到this值时,别忘了有四种方法可以调用函数:作为方法,作为独立(无基础)函数,通过调用/应用和使用new运算符。这意味着:new (o.meth)将返回oo.meth.call(o2, ...)将返回o2o.meth.call(null, ...)将返回undefined最后,如果有人将meth别名为全局变量,则在严格模式支持的环境中,meth()将返回全局对象,而不是undefined,因为cantTouchThis(即null)将不等于(将引用全局对象)。// in global scopevar meth = o.meth;meth(...); // `this` references global object, will return global object(function() { // in local scope var meth = o.meth; meth(...); // `this` is `undefined`, will return `undefined`})();
07-26 09:35