繁体   English   中英

从数组中的对象调用函数(JS)

[英]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 ,它将执行以下两项操作之一:

  1. 如果存在全局定义的Izpis ,它将覆盖此变量。
  2. 如果在当前上下文中未定义Izpis变量,它将在构造函数内部创建一个新变量,此代码块外部将无法访问该变量。

我在您的代码中看到的另一个问题(可能最初并未显示出来)是您正在 IzpisPosodobiIzpis函数使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM