簡體   English   中英

我可以訪問使用 object 構造函數 function 創建的多個對象的參數嗎?

[英]Can I access the parameters of multiple objects created with object constructor function?

我是 js 新手,我試圖了解是否可以訪問使用 object 構造函數 function 創建的所有對象的參數。 例如:我有一個 object 構造函數 function:

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')
}

您可以將它們的集合保存在一個數組中,然后使用some檢查數組中是否有任何(或“一些”)條目與條件匹配:

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

但是你需要那個數組。 構造函數 function 可以創建它,但這通常並不理想; 最好將調用 function 的代碼添加到數組中。

現場示例:

 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"); }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM