gpt4 book ai didi

Javascript 公共(public)成员无法访问

转载 作者:行者123 更新时间:2023-11-28 12:41:17 27 4
gpt4 key购买 nike

我有一个非常简单的结构:

var FORMS = [];

function FormObject(type)
{
this.FormId = FORMS.length;
//alert(this.FormId); returns results 0 and 1 respectively.
this.Type = type;
FORMS.push(FormObject);
this.generate = generate();
}

function generate()
{
return 5;
}

然后我做了这样的事情:

var new_form = new FormObject('fruit');
var another = new FormObject('vegetable');
alert(another.FormId);//as expected, I get 1 as a result

最后尝试做这样的事情:

alert(FORMS.length);//result is 2 so I assume the objects got created successfully
alert(FORMS[0]);//prints the whole code of the constructor into the dialog box

但是当我尝试这样的事情时:

alert(FORMS[0].FormId);//result is undefined!!!
alert(FORMS[0].generate());//it shows an error that the object does not have such method

为什么它是未定义的?我尝试阅读 http://javascript.crockford.com/private.html它说:

Patterns

Public

function Constructor(...) {
this.membername = value;
}
Constructor.prototype.membername = value;

最佳答案

替换:

FORMS.push(FormObject); 

FORMS.push(this);

当您推送 FormObject 对象时,您推送的是构造函数,而不是实例。

关于Javascript 公共(public)成员无法访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12043879/

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