JS如何获取对象的父对象(非文档对象)

JavaScript09

JS如何获取对象的父对象(非文档对象),第1张

在js中,我们时常用到用iframe做系统框架,在子页面也,父页面之间的值传递是一个问题,下面是js获取父窗体和子窗体的对象js:

1.在iframe子页面中获取父页面的元素:

a>window.parent.document这个是获取父页面document中的对象;

b>如果要获取父页面js中的方法:window.parent.xxxx();xxxx()为方法;

2.在父页面中获取iframe子页面中的元素:

a>

var child =

document.getElementByIdx_x("mainFrame").contentWindow//mainFrame这个id是父页面iframe的id

child.document//获取子页面中的document对象;

可以这样

<script type="text/javascript">

var a=function(){

this.x=1

var parent = this

this.b=function(){

this.x=2

alert("parent.x "+parent.x)

}

}

var c=new a()

c.b()

JavaScript 本身是不支持这种查找的, 因为"子对象"只是父对象中的一个引用, 它也可以被其它对象引用, 这样一个"子对象"就可能有多个"父对象". 能实现的是在代码运行中获取它的上级对象.

var Obj = function()

{

    this.child = {

        parent: {},

        get_parent: function()

        {

            return this.parent

        }

    }

    this.init = function()

    {

        this.child.parent = this

    }

    this.init()

}

var o = new Obj

console.log(o.child.get_parent())