[英]Calling function from object in array (JS)
我在从数组中调用函数“ Izpis”时遇到问题。 下列课程:
function Kandidat(ime, priimek, stranka, stDelegatov) {
if (ime == "" || priimek == "") {
alert("Podatki niso popolni!");
return;
} else {
this.ime = ime;
this.priimek = priimek;
this.stranka = stranka;
this.id = polje.length + 1;
this.stDelegatov = stDelegatov;
}
Izpis = function() {
return "(" + this.id + ")" + this.ime + " " + this.priimek + " pripada stranki " + this.stranka + ".";
}
PosodobiIzpis = function(ime, priimek, stranka, stDelegatov) {
this.ime = ime;
this.priimek = priimek;
this.stranka = stranka;
this.stDelegatov = stDelegatov;
}
}
我这样尝试过:
var a = [];
a = a.concat(Isci($("#iskalniNiz")));
for (var i = 0; i < a.length; i++) {
var temp = (Kandidat)(a[i]).Izpis();
$("br:eq(0)").after(temp + "\n");
}
没有(Kandidat)就没有成功。 我收到“未定义”或“不是函数”错误。
在我看来, Kandidat
应该是构造函数。 您定义Izpis
的方式有点粗略...
如果要将Izpis
设置为正在创建的实例的属性(使用new
关键字),则需要编写this.Izpis
。
如果您不this.
前缀this.
,也不使用var
,它将执行以下两项操作之一:
Izpis
,它将覆盖此变量。 Izpis
变量,它将在构造函数内部创建一个新变量,此代码块外部将无法访问该变量。 我在您的代码中看到的另一个问题(可能最初并未显示出来)是您正在 Izpis
和PosodobiIzpis
函数中使用this
。
一旦调用kandidatInstance.Izpis()
以外的函数,此操作就会中断。 例如: setTimeout(kandidatInstance.Izpis)
将不起作用。
要解决此问题,请执行以下任一操作:
function YourConstructor(id) {
// Method 1: store 'this' context in closure
var self = this;
this.yourMethod = function() {
return self.id;
};
// Method 2: explicitly bind 'this' context
this.yourMethod2 = function() {
return this.id;
}.bind(this);
};
// Method 3: use prototype
YourConstructor.prototype.yourMethod3 = function() {
return this.id;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.