从对象实例调用函数不起作用

发布于 2024-12-25 02:17:49 字数 626 浏览 0 评论 0原文

我这里有这个代码:

var myRequest = new httpReq.myRequest(buffer,socket);
if(!myRequest.hasSucceded()){ //return error
    return;
}
arr=myRequest.getCookies();
....

并且我的 myRequest 对象上肯定有这个函数:

function myRequest(buffer, socket) {
    ...
    this.cookies = new Array();
    ...
    //returns the cookie array
    function getCookies() {
        return this.cookies;
    }
    ...
}
exports.myRequest = myRequest;

并且我收到一条错误消息:

TypeError: Object #<myRequest> has no method 'getCookies'

YU NO GIVE COOKIES???

请帮忙...

I have this code here:

var myRequest = new httpReq.myRequest(buffer,socket);
if(!myRequest.hasSucceded()){ //return error
    return;
}
arr=myRequest.getCookies();
....

and i definitely have this function on my myRequest object:

function myRequest(buffer, socket) {
    ...
    this.cookies = new Array();
    ...
    //returns the cookie array
    function getCookies() {
        return this.cookies;
    }
    ...
}
exports.myRequest = myRequest;

and i get an error saying:

TypeError: Object #<myRequest> has no method 'getCookies'

Y U NO GIVE COOKIES???

help please...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

七月上 2025-01-01 02:17:49

您将 getCookies 声明为本地函数。

要从外部调用它,您需要在对象上创建一个属性 getCookies 以便您可以调用它。

试试这个:

function myRequest(buffer, socket) {
...
this.cookies = new Array();
...

//returns the cookie array
this.getCookies = function() {
    return this.cookies;
}

...

}

您也可以只执行 myRequest.cookies 而不是 myRequest.getCookies()

You are declaring getCookies as a local function.

To call it externally, you need to create a property getCookies on your object so you can call it.

Try this:

function myRequest(buffer, socket) {
...
this.cookies = new Array();
...

//returns the cookie array
this.getCookies = function() {
    return this.cookies;
}

...

}

You also could just do myRequest.cookies instead of myRequest.getCookies()

乙白 2025-01-01 02:17:49
function myRequest(buffer, socket) {
    this.cookies = [];
}

myRequest.prototype.getCookies = function () {
    return this.cookies;
};

首先,在构造函数中声明 getCookies 直接导致该方法成为私有方法,仅存在于构造函数中。

其次,通常认为在构造函数之外定义原型 getCookies 是一个好习惯。如果它是在构造函数中定义的(例如,this.getCookies = function () {...}),则每次实例化此原型时都需要初始化此方法。

function myRequest(buffer, socket) {
    this.cookies = [];
}

myRequest.prototype.getCookies = function () {
    return this.cookies;
};

First, declaring getCookies inside constructor directly causes this method to be a private method, which only lives within the constructor.

Second, usually it is considered a good practice to define the prototype getCookies outside the constructor. If it is defined in the constructor (like, this.getCookies = function () {...}), this method would need to be initialized every time when this prototype is instantiated.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文