0

これを行う方法はありますか?

 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()」を呼び出すだけです。

ありがとう!

4

4 に答える 4

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

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

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

jsフィドル

于 2013-01-08T15:01:38.963 に答える
0

それは、関数がどこから呼び出されるかに完全に依存します。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'

readこのインスタンスのメソッドを呼び出して、井戸thisを参照します、このインスタンスのtest

ただし、コードが機能しない場合は、メソッドが別のコンテキストで呼び出されている可能性があります。おそらく、あなたが追加した Eventlistener でしょう。そして、そのコールバック関数が呼び出そうとするとthis.write
thisテスト/関数のインスタンスを参照しなくなります。

また、次のようなローカル変数でコンテキストを保持することもできます

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 

したがって、2 番目のケースでわかるように、コンテキストとしてグローバル オブジェクトで呼び出されますが、writeが実行されます。readWindow

JSBinはこちら

于 2013-01-08T15:18:38.807 に答える
0
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);
}

bind 呼び出しなしで this を使用することもできますが、特定の状況下では「this」の意味が変わる場合があります。

于 2013-01-08T15:03:48.847 に答える
0

これを試して:

function test()
{

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

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

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

フィドル

于 2013-01-08T15:01:49.510 に答える