[英]What is the difference between Object, Object and [1: Object, 2: 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
類型是所有對象的supertype
和subtype
。 這意味着Object
不是本機/內置Object類型的嚴格等價物,但更類似於any
。
@Tushar Acharekar和@Ayush Gupta,謝謝你的回答。
我沒有使用Flow,但是我在這里嘗試了你的代碼: https : //flow.org/try/ ,我收到這條消息: Type argument 'T' is incompatible
。 然后它添加了變量Property 'label' is incompatible
, Property 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.