Function
使用Function构造器生成的函数,并不会在创建它们的上下文中创建闭包;它们一般在全局作用域中被创建。当运行这些函数的时候,它们只能访问自己的本地变量和全局变量,不能访问Function构造器被调用生成的上下文的作用域
这句话我的理解是:通过Function构造器生成的函数是不具有访问该语句所在的上下文的变量,他们一般在全局作用域被创建,只能访问全局作用域下的变量
// 1、f()函数返回的function e()是闭包.
var n = 1;
function f(){
var n = 2;
function e(){
return n;
}
return e;
}
console.log (f()());
//2 作用域链会优先去查找函数e的局部变量,没有找到会向父级作用域查找,然后一直追溯到全局作用域
// 2、f()函数返回的function e()是全局作用域函数
var n = 1;
function f(){
var n = 2;
var e = new Function("return n;");
return e;
}
console.log (f()());
//1 函数e在全局作用域下被创建,所以在访问变量n时返回的是1
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>MDN Example - a recursive shortcut to massively modify the DOM</title>
<script type="text/javascript">
var domQuery = (function() {
var aDOMFunc = [
Element.prototype.removeAttribute,
Element.prototype.setAttribute,
CSSStyleDeclaration.prototype.removeProperty,
CSSStyleDeclaration.prototype.setProperty
];
function setSomething (bStyle, sProp, sVal) {
var bSet = Boolean(sVal), fAction = aDOMFunc[bSet | bStyle << 1],
aArgs = Array.prototype.slice.call(arguments, 1, bSet ? 3 : 2),
aNodeList = bStyle ? this.cssNodes : this.nodes;
if (bSet && bStyle) { aArgs.push(""); }
for (
var nItem = 0, nLen = this.nodes.length;
nItem < nLen;
fAction.apply(aNodeList[nItem++], aArgs)
);
this.follow = setSomething.caller;
return this;
}
//利用闭包的特性将四个工具函数挂载到了oQuery对象相应属性上
//否则需要将工具函数定义到全局作用域下或者是利用Function构造器来定义
function setStyles (sProp, sVal) { return setSomething.call(this, true, sProp, sVal); }
function setAttribs (sProp, sVal) { return setSomething.call(this, false, sProp, sVal); }
function getSelectors () { return this.selectors; };
function getNodes () { return this.nodes; };
return (function (sSelectors) {
var oQuery = new Function('return arguments.callee.follow.apply(arguments.callee, arguments);');
oQuery.selectors = sSelectors;
oQuery.nodes = document.querySelectorAll(sSelectors);
oQuery.cssNodes = Array.prototype.map.call(oQuery.nodes, function (oInlineCSS) { return oInlineCSS.style; });
oQuery.attributes = setAttribs;
oQuery.inlineStyle = setStyles;
oQuery.follow = getNodes;
oQuery.toString = getSelectors;
oQuery.valueOf = getNodes;
return oQuery;
});
})();
</script>
</head>
<body>
<div class="testClass">Lorem ipsum</div>
<p>Some text</p>
<div class="testClass">dolor sit amet</div>
<script type="text/javascript">
domQuery('.testClass')
//这里能链式调用,也是因为工具函数返回了调用对象
.attributes('lang', 'en')('title', 'Risus abundat in ore stultorum')
.inlineStyle('background-color', 'black')('color', 'white')('width', '100px')('height', '50px');
</script>
</body>
</html>