gpt4 book ai didi

javascript - TypeError : this. 名称不是函数

转载 作者:行者123 更新时间:2023-12-03 05:39:59 25 4
gpt4 key购买 nike

在下面的代码中,即使上面定义了该函数,我总是收到错误“TypeError: this.verifyUrl is not a function at Server.ImageServer.handleRequest”。

欢迎任何提示。

如果我用纯 JavaScript 编写示例,同样适用。

"use strict";

import Http = require('http');
import Url = require('url');

export class ImageServer {

port: number;
server: Http.Server;

constructor(port: number) {
this.port = port || 1337;
}

run() {
this.server = Http.createServer(this.handleRequest);
this.server.listen(this.port);
}

verifyUrl(urlitems: Url.Url) {
return true;
}

handleRequest(req: Http.IncomingMessage, res: Http.ServerResponse) {
console.log('request: ', req.url);
var urlitems = Url.parse(req.url, true);
var pathitems = urlitems.path.split('/').slice(1);

console.log('url: ', urlitems);
console.log('path: ', pathitems);

if (!this.verifyUrl(urlitems)) {
this.sendNotFound(res);
return;
}

res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
}

sendNotFound(res: Http.ServerResponse) {
res.statusCode = 404;
res.end();
return undefined;
}

}

最佳答案

试试这个:

"use strict";

import Http = require('http');
import Url = require('url');

export class ImageServer {

port: number;
server: Http.Server;

constructor(port: number) {
this.port = port || 1337;
}

run() {
this.server = Http.createServer(this.handleRequest);
this.server.listen(this.port);
}

verifyUrl(urlitems: Url.Url) {
return true;
}

handleRequest = (req: Http.IncomingMessage, res: Http.ServerResponse) => {
console.log('request: ', req.url);
var urlitems = Url.parse(req.url, true);
var pathitems = urlitems.path.split('/').slice(1);

console.log('url: ', urlitems);
console.log('path: ', pathitems);

if (!this.verifyUrl(urlitems)) {
this.sendNotFound(res);
return;
}

res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
}

sendNotFound(res: Http.ServerResponse) {
res.statusCode = 404;
res.end();
return undefined;
}

}

我想您将 handleRequest 作为来自模块的回调调用(可能是 expressjs?),因此 this 未绑定(bind)到类范围但在模块的范围内。使用箭头函数,this 将自动分配给类范围,因此您可以访问类函数/属性

这是通过示例解释您的问题

class Hi {
hello: string = "Hello world!";

haha(req: Http.IncomingMessage, res: Http.ServerResponse) {
console.log(this.hello) // print undefined or error
}
}

var hi = new Hi();

app.get("/foo", hi.haha);

使用此代码,您无法访问类属性,因为 this 已分配给express。

您可以按照上面所述使用箭头函数修复它。这是一个有效的示例:

class Hi {
hello: string = "Hello world!";

haha = (req: Http.IncomingMessage, res: Http.ServerResponse) => {
console.log(this.hello) // print Hello world!
}
}

var hi = new Hi();

app.get("/foo", hi.haha);

关于javascript - TypeError : this. 名称不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40578015/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com