最近,我对 {}
和 Object
之间的区别感到困惑。有时,{}
可以解决我的问题,但有时它无法解决问题并且我需要使用 Object
。我真的不知道原因。
我做了一些测试,希望可以给你一些提示。
const t: Array<{label: string}> = [{label:'1'}];
const arr: Array<{}> = t; //error
const arr2: Array<Object> = t; //pass
最近,我对 {}
和 Object
之间的区别感到困惑。有时,{}
可以解决我的问题,但有时它无法解决问题并且我需要使用 Object
。我真的不知道原因。
我做了一些测试,希望可以给你一些提示。
const t: Array<{label: string}> = [{label:'1'}];
const arr: Array<{}> = t; //error
const arr2: Array<Object> = t; //pass
在Flow中,数组是不变的。
class A {}
class B extends A {}
var bs: Array<B> = [];
var as: Array<A> = bs;
as.push(new A); // this would be bad!
{}
是 new Object()
的别名。
因此,可以说 Object
是一个 class
,而 {}
是该类的一个 instance
。
您可以在这里看到:
console.log(JSON.stringify(new Object()) == JSON.stringify({}))
console.log({} instanceof Object)
我没有使用Flow,但我在这里尝试了你的代码:https://flow.org/try/,然后我得到了这个消息:Type argument 'T' is incompatible
。然后它添加了变量Property 'label' is incompatible
和Property not found
。
我猜是因为t
是一个Sealed Objects数组,而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
数据对时使用{}
。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.
方法一:
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
方法二:
var Obj = function(name) {
this.name = name
}
var c = new Obj("hello");
掌握JavaScript是学习
javascript原型
最好的视频。
{}
和Object
之间的用法差异。 - Tushar Acharekar
{}
is an alias fornew Object()
- Ayush Gupta