在javascript中访问函数和嵌套函数之间的区别

时间:2012-06-14 13:31:22

标签: javascript oop

我试图找出为什么我不能以类似的方式访问嵌套函数,因为我只是访问一个非嵌套函数(也许有更好的解释方法。

换句话说,这有效:

<html>
<head>
<title>Working with elements</title>
</head>

<script type="text/javascript">
var my_div = null;
var newDiv = null;

function addElement()
{
  // create a new div element
  // and give it some content
  newDiv = document.createElement("div");
  newContent = document.createTextNode("Hi there and greetings!");
  newDiv.appendChild(newContent); //add the text node to the newly created div.

  // add the newly created element and it's content into the DOM
  my_div = document.getElementById("org_div1");
  document.body.insertBefore(newDiv, my_div);
}

</script>

<body onload="addElement()">
<div id='org_div1'> The text above has been created dynamically.</div>
</body>
</html>

这不起作用:

<html>
<head>
<title>Working with elements</title>
</head>

<script type="text/javascript">
var my_div = null;
var newDiv = null;

function addElement()
{
    this.getFieldset = function() {
        // create a new div element
        // and give it some content
        newDiv = document.createElement("div");
        newContent = document.createTextNode("Hi there and greetings!");
        newDiv.appendChild(newContent); //add the text node to the newly created div.

        // add the newly created element and it's content into the DOM
        my_div = document.getElementById("org_div1");
        document.body.insertBefore(newDiv, my_div);
    }
}

</script>

<body onload="addElement.getFieldSet()">
<div id='org_div1'> The text above has been created dynamically.</div>
</body>
</html>

1 个答案:

答案 0 :(得分:4)

这是因为您在第二种情况下从未执行addElement()以执行this.getFieldset = ...分配。

您可以将代码更改为

function addElement() {}

addElement.getFieldSet = function() {
        // create a new div element
        // and give it some content
        newDiv = document.createElement("div");
        newContent = document.createTextNode("Hi there and greetings!");
        newDiv.appendChild(newContent); //add the text node to the newly created div.

        // add the newly created element and it's content into the DOM
        my_div = document.getElementById("org_div1");
        document.body.insertBefore(newDiv, my_div);
    };

修改

请参阅此fiddle的示例。