首页 > 解决方案 > JS 中的这种语言结构是什么?

问题描述

你能帮我理解一下Javascript中的这个吗?什么是a,什么是a['b']?如何在 iframe 和父窗口中访问构造的声明内容?

var a = window['parent'];
if(a) {
    if(a['b']){
        a['b']({
            "c": 1,
            "d": {
                "e": "f",
                "g": false,
                "h": 1
            },
            "i": 0,
            "j": true
        });
    }
}

如果可能的话,请给我一个链接,我可以在其中阅读有关此构造的信息。

非常感谢。

标签: javascript

解决方案


好吧,无论如何,那里没有好的问题,看来您真的很想弄清楚,所以我会回答:

var a = window['parent']; // here we access the "parent" property of window. Could as well be accessed as "window.parent" (same results)
if(a) { // here we check if "a" is truthy [1]
    if(a['b']){ // here we assume that "a" is an object [2] (associative array in some languages), because we are accessing its "b" property. Also we are checking if the "b" property is truthy. 
        a['b']({ // here we assume that a['b'] is a function, because  parentheses are used. We then pass an object (denoted by curly braces) as an argument.
            "c": 1, // this is object's property (as well as others below)
            "d": { // the nested (child) object begins
                "e": "f",
                "g": false,
                "h": 1
            },
            "i": 0,
            "j": true
        });
    }
}

[1] 真实 - https://developer.mozilla.org/en-US/docs/Glossary/Truthy

[2] 对象 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

PS 一般来说,这是一个糟糕的代码。你永远不应该尝试以这种方式编写代码。事情可能会出错,例如 a['b'] 可能不是函数而是其他一些真实的类型。而且这整件事显然是不可读的。


推荐阅读