访问同一函数内的其他函数

Access other functions inside the same function

本文关键字:函数 其他 访问      更新时间:2023-09-26

有什么方法可以做到这一点吗?

 function test()
    {
        this.write = function(text)
        {
            alert(text);
        }
        this.read = function()
        {
            this.write('foo');
            // WRONG WAY
            // test.write('foo');
        }
    }

如何从"this.read"调用"this.write"函数?

编辑:

找到了EricG的awnser。已经尝试过上面的代码,它是有效的。但我的真实代码仍然不起作用。我必须弄清楚发生了什么。

从"THIS.READ"内部调用"THIS.WRITE"的方法就是调用"THIS.WRITE(("。就像那样。

谢谢!

function test()
{
    this.write = function(text)
    {
        alert(text);
    }
    this.read = function()
    {
        this.write('foo');
    }
}
var a = new test();
a.read();

jsFiddle

试试这个:

function test()
{
    this.write = function(text)
    {
        alert(text);
    }
    this.read = function()
    {
        this.write('foo');
    }
}
var t = new test();
t.read();

小提琴

function test()
{
   var self = this;
    this.write = function(text)
    {
        alert(text);
    };
    this.read = function()
    {
        self.write('foo');
    };
    // depending on browser versions or included libraries.
    this.another = function () {
        this.write('foo');
    }.bind(this);
}

您也可以在不使用绑定调用的情况下使用它,但在某些情况下,"this"的含义可能会更改。

这完全取决于从哪里调用函数。我建议阅读更多关于this关键字的内容也许可以看看这个SO问题

如果创建test 的实例

function test()
{
    this.write = function(text)
    {
        alert(text);
    }
    this.read = function()
    {
        this.write('foo');
    }
}
var inst = new test()
inst.read() //foo
inst.read.call() //Uncaught TypeError: Object [object Window] has no method 'write'

并调用此实例的方法readthis将引用,此实例为test

但是,如果您的代码不起作用,则可能会使用另一个上下文调用该方法。也许是您添加的Eventlistener。它的回调函数尝试调用this.write
那么CCD_ 7将不再引用test/your函数的实例。

您还可以将上下文保存在像这样的局部变量中

function test()
{
    var context = this;
    this.write = function(text)
    {
        alert(text);
    }
    this.read = function()
    {
        context.write('foo');
    }
}
var inst = new test()
inst.read() // foo
inst.read.call() //foo 

因此,正如您在第二种情况中看到的那样,尽管read是以全局对象Window作为其上下文来调用的,但write会被执行。

这是一个JSBin