Javascript 访问同一函数中的其他函数

Javascript 访问同一函数中的其他函数,javascript,Javascript,有办法做到这一点吗 function test() { this.write = function(text) { alert(text); } this.read = function() { this.write('foo'); // WRONG WAY // test.write('foo');

有办法做到这一点吗

 function test()
    {

        this.write = function(text)
        {
            alert(text);
        }

        this.read = function()
        {
            this.write('foo');
            // WRONG WAY
            // test.write('foo');
        }
    }
如何从“this.read”调用“this.write”函数

编辑:

埃里克找到了奥恩瑟。我已经尝试了上面的代码,它的工作。但我真正的代码仍然不起作用。我得弄清楚发生了什么事

从“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();
试试这个:

function test()
{

    this.write = function(text)
    {
        alert(text);
    }

    this.read = function()
    {
        this.write('foo');
    }
}

var t = new test();
t.read();


您也可以在不使用bind调用的情况下使用此函数,但在某些情况下,“this”的含义可能会改变。

这完全取决于调用函数的位置。 我建议多读一些关于
this
关键字的内容,也许可以看看这个

如果创建
测试的实例

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'
并调用此实例的方法
read
this
将引用井,
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'
但是,如果代码不起作用,则可能会使用其他上下文调用该方法。 可能是您添加的一个Eventlistener。它的回调函数尝试调用this.write

然后,
这个
将不再引用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 
因此,正如您在第二种情况下所看到的,
write
被执行,尽管
read
是以全局对象
Window
作为上下文调用的


这里有一个

首先是如何调用
test
的?如何调用
read
的?这将决定
这个
在每个函数中的值。你为什么使用
这个
?你是否将
test
作为构造函数调用?如果是,为什么不使用启动构造函数的约定带大写字母的e(即
函数Test()
)?如果你想做
新测试(),请使用
this.write()
。read()
圣母玛利亚…我尝试了很多次这样做,并用“this.foo()”来执行另一个函数。这个例子可以使用,但出于某种原因,我的代码(其他代码,我没有放在这里)不管怎样,它不起作用了。谢谢艾克和昆汀的帮助