2

我在面向对象方面遇到了困难。看看下面的代码:

SomeClass = function(){
        this.sanityCheck = 0;

        this.createServer = function(){
            console.log('creating server');
            require('http').createServer(
                this.onRequest
            ).listen(
                8080
            );
            console.log('server created');
        }

        this.onRequest = function(req , res){
            console.log('request made');
            res.writeHead( 200 , {'content-type' : 'text/plain'} );
            var d = new Date();
            res.write('Hello World! \n' + d.toString() + '\n');
            console.warn( this.sanityCheck ); // <!> MY ISSUE
            res.end();
            console.log('response sent');
        }
};

var obj1 = new SomeClass();
obj1.createServer();

该行 console.warn( this.sanityCheck ); 显示undefined在控制台上。如何获取 函数obj1 内部 this.onRequest (原件,而不是副本)?

提前感谢一堆。

4

1 回答 1

5

Http.createServer 不知道您的对象...因此您必须在发送之前将方法绑定到它:

createServer(
                this.onRequest.bind( this )
            )

无关提示:您可以将方法移到原型之外,而不是堆积缩进。

于 2013-08-08T18:14:00.033 回答