根据this blog post,可以引用DOM元素作为window
对象的命名属性(基于它们的name
属性)。上面的代码显示表格的确可以作为window.aform
访问。但是,为什么在迭代window
的所有属性时找不到属性?引用DOM元素作为窗口对象的属性
<html>
<body>
<form name='aform'>
</form>
<script>
// get all properties, including non-enumerable ones: http://stackoverflow.com/a/8024294/274677
function getAllProperties(obj){
var allProps = [], curr = obj;
do {
var props = Object.getOwnPropertyNames(curr)
props.forEach(function(prop){
if (allProps.indexOf(prop) === -1)
allProps.push(prop)
})
} while(curr = Object.getPrototypeOf(curr))
return allProps
}
var findIn = function(x,y) {
var ps = getAllProperties(x);
for (var i = 0 ; i < ps.length; i++) {
var propertyName = ps[i];
try {
if (x[propertyName]===y)
return 'found as property ['+propertyName+']';
} catch (e) {
console.log('failed to read property ['+propertyName+'] due to: ['+e.name+']');
}
}
return "not found";
}
console.log(findIn(window, window.aform));
console.log(window['aform']===window.aform);
console.log(window.aform);
</script>
</body>
</html>
当上述页面加载,我看到控制台上:
not found
true
<form name="aform"></form>
当试图读取窗口对象中的所有属性时,我在'findIn'函数中尝试Firefox时遇到错误'SecurityError:操作不安全.'。 – Guffa
@Guffa在Plunker中尝试时出现类似错误:http://plnkr.co/edit/AAlQkzO5BYdwRR1f8NdL。当从本地文件系统中通过Chrome打开文件时,我能够毫无例外地看到控制台输出。 –
@Guffa更新了代码(在上面给出的链接中的Plunker中),以便在发生'SecurityError'时它不会脱离循环。 –