【问题标题】:JS - Property of object with assigned value becomes undefinedJS - 具有赋值的对象的属性变得未定义
【发布时间】:2020-03-19 01:21:09
【问题描述】:

我正在尝试在 js 中运行此代码

    function platform() {
       platform.list.push(this);
       //some more code
    }
    platform.lf = false;

我将所有平台实例都存储在 platform.list 上。但是当我尝试这样做时:

    console.log(platform.list[0].lf);

我没有定义?有什么帮助吗? (我确实有一个平台对象实例)

【问题讨论】:

  • @BorisLipschitz,如果这是一个带有 list 属性的构造函数,它是一个数组,那没关系,但我猜 OP 没有 list 属性,那不是构造函数,否则 OP 将使用 this.list.push 代替。话又说回来……谁知道呢。没有足够的代码来回答这个问题。哦,@CroquetFlamingo,平台只是一个函数,而不是一个对象。如果是构造函数需要调用new platform来创建一个Object。此外,您应该按照惯例将构造函数的第一个字符大写。
  • @StackSlave 因为我的第一条评论相当愚蠢(没有正确阅读 OP)并且因为最可能的答案是他只是没有意识到“platform.lf”和“this.lf " 不是一回事,我正在删除我以前的 cmets :-)

标签: javascript object properties


【解决方案1】:

这是你想要做的吗?为什么它似乎在 sn-p 上运行良好?您是否忘记在您的“//一些更多代码”部分中初始化 lf (this.lf = ...),这是您没有发布的部分?

只是附带说明 - platfrom.lf 和属于类实例的 lf(您尝试访问的实例)是完全不同的东西。

test.list = []

function test()
{
  test.list.push(this);
  this.x = Math.random();
}

a = new test();
b = new test();

console.log(test.list.length);
console.log(test.list[0].x);
console.log(test.list[1].x);

【讨论】:

    【解决方案2】:

    这可能是您需要学习的内容。如果你正在创建一个构造函数(由于私有变量的原因,我现在推荐它而不是类),在你调用new 之前它不是一个对象。

    function Platform(){
      const a = ['lame', 1, 'test']; // private array
      this.lf = true;
      this.testFunc = ()=>{
        // no arguments array in an arrow function
        console.log(a);
        return this; // for property chaining
      }
    }
    function Platforms(){
      this.list = [];
      this.addPlatform = function(){
        this.list.push(...arguments);
        return this;
      }
    }
    const pf = new Platforms, np = new Platform;
    np.lf = false;
    pf.addPlatform(new Platform, new Platform, np);
    pf.list[0].lf = false;
    console.log(pf.list); np.testFunc();

    您可能还想看看这个设计:

    function Platform(){
      this.lf = true;
    }
    function Platforms(){
      this.list = [];
      this.addPlatform = function(){
        this.list.push(new Platform);
        return this;
      }
    }
    const pf = new Platforms;
    pf.addPlatform().addPlatform().addPlatform();
    pf.list[0].lf = false;
    console.log(pf.list);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-21
      • 1970-01-01
      • 2016-06-15
      相关资源
      最近更新 更多