1

我只是写了一个测试html文件来了解javascript中的对象。代码如下

在脚本标签中

<script type="text/javascript">

    var obj = new ParentFn();
    var obj2 = new AnotherParentFn();
    var temp;
    function initer()
    {
        temp = obj.Adding();
        obj2.caller();
    }
    function ParentFn()
    {
        this.a = 10;
        this.b = 20;
    }
    function AnotherParentFn()
    {
        this.a = 30;
        this.b = 50;
    }
    AnotherParentFn.prototype.caller = function()
    {
        var self = this;
        temp();
    }
    ParentFn.prototype.Adding = function()
    {
        var self = this;
        document.getElementById("id_div1").innerHTML = " Method Called and Result of a+b is " + (self.a + self.b);          
    }

</script>

在我使用的身体

<button onclick="initer()"> Click here to test </button>
<div id="id_div1"></div>

问题是当从 initer() 函数调用 AnotherParentFn.prototype.caller 时,临时变量仍未定义。代码有什么问题??

我的任务是在全局变量中分配函数 ParentFn.prototype.Adding 并从 AnotherParentFn.prototype.caller 函数中调用全局变量。如何实现?

4

4 回答 4

1

您不需要将其保存为全局变量。它已经保存在ParentFn.prototype. 您需要做的就是调用它.call并传入您想要的接收器。你可以AnotherParentFn.prototype.caller这样实现:

AnotherParentFn.prototype.caller = function()
{
    ParentFn.prototype.Adding.call(this);
}

temp这样你就可以彻底摆脱。您也不需要在任何地方分配this给本地人var self

于 2013-04-02T06:19:21.057 回答
0

通过编写 temp = obj.Adding(); 它存储返回值。不是函数指针temp。用这个

function initer()
{
    temp = obj.Adding;
    obj2.caller();
}
于 2013-04-02T06:03:00.953 回答
0

括号用于执行函数。当您将值分配给 时temp,您正在调用该函数并将结果(undefined)分配给temp。要在 中存储对函数的引用temp,请省略括号。

temp = obj.Adding;
于 2013-04-02T06:03:29.737 回答
0

首先,obj.Adding没有正确分配对的引用;应该是这样的(不带括号):

function initer()
{
    temp = obj.Adding;
    obj2.caller();
}

然后,在其内部,您必须在调用期间通过使用显式AnotherParentFn.prototype.caller传递当前对象:this.call()

AnotherParentFn.prototype.caller = function()
{
    temp.call(this);
}
于 2013-04-02T06:10:14.307 回答