【问题标题】:Can I access the parameters of multiple objects created with object constructor function?我可以访问使用对象构造函数创建的多个对象的参数吗?
【发布时间】:2020-07-02 15:09:07
【问题描述】:

我是 js 新手,我试图了解是否可以访问使用对象构造函数创建的所有对象的参数。例如: 我有一个对象构造函数:

function objectconstructor (width){
    this.color=width;
    this.element = document.createElement('div')
    element.style.backgoundColor = this.width + 'px';
}
// Now I have two objects created with the objectconstructor:
var object1 = new objectconstructor (100)
var object2 = new objectconstructor (200)

// Now I have the following function 
function () {
    if((object1.width>100) || (object2.width>100)){
        alert('hi')
    }
}

我想缩短 if 语句,例如:

if (All_objects_created_with_object_constructor_function.width > 100) {
  alert('hi')
}

【问题讨论】:

  • 不,如果没有您自己的维护初始化值列表的代码,您将无法做到这一点。
  • 由于属性的值可以稍后更改,您能否详细说明您要检查当前值还是初始值(width 参数)?此外,您拥有的代码和您想要的代码并不相同。当前代码中的条件在至少一个对象的width 大于100 时通过,目标是所有对象的宽度都应大于100。哪一个是正确的?

标签: javascript parameter-passing


【解决方案1】:

您可以将它们的集合保存在一个数组中,然后使用some 检查数组中是否有任何(或“一些”)条目符合条件:

if (theArray.some(({width}) => width > 100)) {
    alert("Hi");
}

但是你需要那个数组。构造函数可以创建它,但这通常并不理想;最好将调用函数的代码添加到数组中。

现场示例:

function Thingy(width) {
    this.width = width;
//       ^−−−−−−−−−−−−−− `this.width`, not `this.color`
    this.element = document.createElement('div');
    this.element.style.backgoundColor = this.width + 'px';
//  ^−−−−−−−−−−−−−− Added missing `this.` here
}

// Create Thingys
const thingies = [
    new Thingy(50), // 50 instead of 100 just to show we're not just checking the first one later
    new Thingy(200),
];

if (thingies.some(({width}) => width > 100)) {
    console.log("At least one Thingy matches");
} else {
    console.log("No Thingys match");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-30
    相关资源
    最近更新 更多