簡體   English   中英

如何在 JavaScript 中創建對象

[英]How to create objects in JavaScript

我想創建具有屬性的對象:

{
type,
geometry: {
  type,
  coordinates;
}
}

我試圖通過構造函數創建它:

function element(x, u) {
    this.type = 'type';
    this.geometry.type = 'type';
    this.geometry.coordinates = [x, y];
}

事實上,我不能那樣做。

我需要如何以正確的方式創建這些對象?

你的代碼有一個錯字( u -> y ); 此外,如果this.geometry未定義,則不能分配this.geometry.type

function element(x, y) {
    this.type = 'type';
    this.geometry = {};
    this.geometry.type = 'type';
    this.geometry.coordinates = [x, y];
}

還可以考慮查看class es。

對於您提供的對象結構,您可以像這樣簡單:

var yourNewObject = {
    type: 'typeValue',
    geometry: {
      type: 'geometryTypeValue',
      coordinates 'coordinatesValue';
    }
  }

如果你想以構造函數風格創建一個對象,那么你可以做這樣的事情。

 function element(x, y, type) { this.type = 'type'; this.geometry = new Geometry(); function Geometry() { this.coordinates = [x, y]; this.type = type; } } var el = new element(1, 2, 'mytype'); console.log(el);

您可以遞歸地使用 JS 提供的一些對象 API 來創建對象並將其添加到任何其他對象,例如 -

Object.defineProperties()    
Object.defineProperty()
Object.assign()
Object.create()
.....
.....

暫無
暫無

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

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