gpt4 book ai didi

javascript - 在 JavaScript 中使用默认值创建自定义对象数组

转载 作者:行者123 更新时间:2023-11-28 01:42:43 25 4
gpt4 key购买 nike

所以我想做的是一组自定义对象。所以我有一个构造函数,但我不通过参数传递值,而是想将所有值初始化为 0 并使用 getter 或 setter 来检索它们。显然,它不起作用,但我不知道为什么。我所看到的所有对象都是通过参数传递值来创建的,所以我只是猜测。

我的构造函数

    function Stol()
{
var cipsy = 0, kofca = 0, dzus = 0, sypcaj = 0, vrecaj = 0, coko = 0,jedlo = 0, pernik = 0, kava = 0, ucet = 0;
this.cipsy = cipsy;
this.kofca = kofca;
this.dzus = dzus;
this.sypcaj = sypcaj;
this.vrecaj = vrecaj;
this.coko = coko;
this.jedlo = jedlo;
this.pernik = pernik;
this.kava = kava;
this.ucet = ucet;

this.reset = reset;
function reset() {
this.cipsy = 0;
this.kofca = 0;
this.dzus = 0;
this.sypcaj = 0;
this.vrecaj = 0;
this.coko = 0;
this.jedlo = 0;
this.pernik = 0;
this.kava = 0;
Obrat += this.ucet;
this.ucet = 0;
}
this.addItem = addItem;
function addItem(type, number) {
switch (type) {
case 0 : this.cipsy += number; break;
case 1 : this.kofca += number; break;
case 2 : this.dzus += number; break;
case 3 : this.sypcaj += number; break;
case 4 : this.vrecaj += number; break;
case 5 : this.coko += number; break;
case 6 : this.jedlo += number; break;
case 7 : this.pernik += number; break;
case 8 : this.kava += number; break;
}
}
this.getItem = getItem;
function getItem(type) {
var item;
switch (type) {
case 0 : item = this.cipsy; break;
case 1 : item = this.kofca; break;
case 2 : item = this.dzus; break;
case 3 : item = this.sypcaj; break;
case 4 : item = this.vrecaj; break;
case 5 : item = this.coko; break;
case 6 : item = this.jedlo; break;
case 7 : item = this.pernik; break;
case 8 : item = this.kava; break;
}
return item;
}
}

然后我在这里创建数组

var stol = new Array();
for (var i = 0; i < 14; i++) {
stol[i] = new Stol();
}

最终我想像这样使用 jQuery 修改一些跨度。 #selecStol是一个下拉列表(切换未完成)。

$("#selecStol").change(function(){
var myStol = stol[$(this).find(":selected").val()];
for (i = 0; i < 14; i++) {
switch (i) {
case 0 : $("#cipsy").text(myStol.getItem(i));break;

}
}
})

但它不起作用,我不知道哪一部分。

最佳答案

那是因为 getter 函数中的 this 并不是您所想的那样。

如果您在开发工具中检查 this,您可能会看到窗口对象。要解决这个问题,您可以将 this 保存在像这样的 var 中:

function Stol(){
var self = this;
//All your variable "this"
this.getItem = function(type){
//In this function you use self instead of this
//ex : case 0 : item = self.cipsy; break;
}
}

或者推荐的方式,使用原型(prototype):

function Stol(){
//Your things
}

Stol.prototype.getItem = function(type){
//Now "this" will be Stol object.
}

请注意,我仅使用 getItem 函数作为答案,但您的所有其他函数都有相同的问题。

关于javascript - 在 JavaScript 中使用默认值创建自定义对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20687221/

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