簡體   English   中英

{}和Object之間有什么區別?

[英]What is the difference between {} and Object?

最近,我對{}Object之間的區別感到困惑。 有時, {}會解決我的問題,有時,它不能和我用Object切換。 我真的不知道為什么。

我做了一些測試,希望它可以給你一些提示。

const t: Array<{label: string}> = [{label:'1'}];
const arr: Array<{}> = t; //error
const arr2: Array<Object> = t; //pass

{}new Object()的別名。

所以你可以說Object是一個class{}是該類的一個instance

你可以在這里看到:

 console.log(JSON.stringify(new Object()) == JSON.stringify({})) console.log({} instanceof Object) 

我覺得這個答案比較合理Github鏈接:[混合型]超類型bug

數組在Flow中是不變的

class A {}
class B extends A {}
var bs: Array<B> = [];
var as: Array<A> = bs;
as.push(new A); // this would be bad!

我斷言Array<B>應的子類型Array<A>如果A是的超類型A是不正確的

Object是一個例外,

Object類型是所有對象的supertypesubtype 這意味着Object不是本機/內置Object類型的嚴格等價物,但更類似於any

@Tushar Acharekar和@Ayush Gupta,謝謝你的回答。

我沒有使用Flow,但是我在這里嘗試了你的代碼: https//flow.org/try/ ,我收到這條消息: Type argument 'T' is incompatible 然后它添加了變量Property 'label' is incompatibleProperty not found

我猜是因為t是一個密封對象的數組,但是arr是一個Unsealed Objects數組。

現在,當你將t分配給arr2時,它可以工作,因為arr2只是一個(普通Javascript)對象的數組。 您也可以將一個未密封的對象數組分配給arr2 或者推動arr2混合密封和未密封的物體。

請注意這些通行證:

const t: Array<{label: string}> = [{label:'1'}];
const t1: {label: string} = {label: `1`};
const w: Array<{label: string}> = [t1];
const t2: {label: string} = {label: `2`};
w.push(t2);

但這不會通過:

let w: Array<{label: string}> = [];
const t3: {} = {};
w.push(t3);

但這些將通過:

const u: Array<Object> = [{label:'1'}];
const arr: Array<{}> = u;   

const v: Array<{}> = [{label:'1'}];
const arr2: Array<Object> = v;  

const t3: {foo: number} = {foo:1};
arr2.push(t3);

對象是屬性的集合,屬性是名稱(或鍵)與值之間的關聯。 屬性的值可以是函數,在這種情況下,屬性稱為方法。

  • 在生成key:value paire數據的情況下,我更喜歡使用{}
  • 我更喜歡使用new Object()來創建像Method1, Method2這樣的復雜對象

請看下面的例子

var d = new Object();           //This is the simplest way to create an empty object.
var a = Object.create(null);    //This method creates a new object extending the prototype object passed as a parameter.
var b = {};                     //This is equivalent to Object.create(null) method, using a null prototype as an argument.

方法1:

var Animal = {
  type: 'Invertebrates',  // Default value of properties
  displayType: function() {  // Method which will display type of Animal
    console.log(this.type);
  }
};
var animalObject = Object.create(Animal);
animalObject.displayType();         // Output:Invertebrates
var fish = Object.create(Animal);
fish.type = 'Fishes';
fish.displayType();                 // Output:Fishes

方法2:

var Obj = function(name) {
  this.name = name
}
var c = new Obj("hello"); 

Dicoverign Javascript是學習javascript prototype最佳視頻

暫無
暫無

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

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