【问题标题】:Javascript Object Instances lose function access on Array RecallJavascript 对象实例在 Array Recall 上失去函数访问权限
【发布时间】:2019-03-05 23:52:21
【问题描述】:

我有以下代码示例:

var cobj = {
  a: 0,
  b: 0,
  c: 0,
  asdinit: function(x, y, w, h) {
    this.a = x;
    this.b = y;
    this.c = w;
    this.h = h;
  },
  adsfads: function(a, b, c, d) {
    this.a = a;
    this.b = b;
    this.c = c;
  }
}

var c = new cobj.asdinit(1, 1, 1, 1);
var bigarray = []
for (t = 0; t < 10; t++) {
  var newobj = new cobj.asdinit(1, 1, 1, 1);
  bigarray.push(newobj);
}
for (t = 0; t < 10; t++) {
  var localobj = bigarray[t];
  localobj.adsfads(1, 1, 1, 1);
}

在对象创建时 - 所有函数都可以调用。在从数组中调用之后,函数不可用?

【问题讨论】:

    标签: javascript arrays object prototype


    【解决方案1】:

    您需要重新编写代码,以便函数返回您的对象。

    var cobj = function() {
      return {
        a: 0,
        b: 0,
        c: 0,
        asdinit: function(x, y, w, h) {
          this.a = x;
          this.b = y;
          this.c = w;
          this.h = h;
        },
        adsfads: function(a, b, c, d) {
          this.a = a;
          this.b = b;
          this.c = c;
        }
      }
    }.bind(this)
    
    vat cobjInstance = cobj();
    var c = cobjInstance.asdinit(1, 1, 1, 1);
    var bigarray = []
    for (t = 0; t < 10; t++) {
      var newobj = new cobjInstance.asdinit(1, 1, 1, 1);
      bigarray.push(newobj);
    }
    for (t = 0; t < 10; t++) {
      var localobj = bigarray[t];
      localobj.adsfads(1, 1, 1, 1);
    }
    
    

    【讨论】:

      【解决方案2】:

      您正在使用 asdinit 和 adsfads 函数作为构造函数。从每个构造创建的对象只有a、b 和c 属性。它们没有任何原型方法。

      我认为你真正追求的是

      class cobj {
        constructor (x, y, w, h) {
          this.a = x
          this.b = y
          this.c = w
          this.h = h
        }
        
        adsfads (a, b, c, d) {
          this.a = a
          this.b = b
          this.c = c
        }
      }
      
      var bigarray = []
      for (t = 0; t < 2; t++) {
        var newobj = new cobj(t, t, t, t);
        bigarray.push(newobj);
      }
      for (t = 0; t < 2; t++) {
        var localobj = bigarray[t];
        localobj.adsfads(t + 1, t + 1, t + 1, t + 1);
        console.log(localobj)
      }

      见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes


      ES5 的等价物类似于

      function cobj(x, y, w, h) {
        this.a = x
        this.b = y
        this.c = w
        this.h = h
      }
      
      cobj.prototype.adsfads = function(a, b, c, d) {
        this.a = a
        this.b = b
        this.c = c
      }
      

      【讨论】:

      • 谢谢,我意识到此时我需要类和构造函数,但使用其他语法似乎无法实现。
      猜你喜欢
      • 2021-04-19
      • 1970-01-01
      • 2021-12-02
      • 2022-01-05
      • 2010-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多