2015-10-05 52 views
0

根据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> 
+0

当试图读取窗口对象中的所有属性时,我在'findIn'函数中尝试Firefox时遇到错误'SecurityError:操作不安全.'。 – Guffa

+0

@Guffa在Plunker中尝试时出现类似错误:http://plnkr.co/edit/AAlQkzO5BYdwRR1f8NdL。当从本地文件系统中通过Chrome打开文件时,我能够毫无例外地看到控制台输出。 –

+0

@Guffa更新了代码(在上面给出的链接中的Plunker中),以便在发生'SecurityError'时它不会脱离循环。 –

回答

1

某些浏览器添加的形式引用作为属性的window对象,有的只使其可用,这样你可以阅读它就像一个属性,但它并不实际添加为属性。

当我在Firefox中尝试它时发现该属性,但在Chrome,IE和Edge中找不到。

通过名称获取表单的最安全方法是使用document.forms集合,其中明确定义了表单可用。

+0

“只能使它可用,以便您可以像读取属性一样阅读它,但它实际上并未作为属性添加。”这是如何完成的? –

+0

@MarcusJuniusBrutus:可能通过让属性读取器从其他集合中读取,类似于早期IE中的window.all集合如何从其他集合中读取。为了精确地回答这个问题,您需要深入了解每个浏览器的实际实现。 – Guffa

相关问题