NodeJS上的面向对象问题

bla*_*gus 2 oop node.js

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

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();
Run Code Online (Sandbox Code Playgroud)

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

提前感谢一堆.

Esa*_*ija 5

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

createServer(
                this.onRequest.bind( this )
            )
Run Code Online (Sandbox Code Playgroud)

不相关的提示:您可以在原型上移动方法,而不是堆积在缩进上.