gpt4 book ai didi

javascript - JavaScript 对象创建方法有什么区别?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:41:26 25 4
gpt4 key购买 nike

我一直在尝试更深入地学习 Javascript 中的 OOP。在 JavaScript 中创建类和对象的方法有多种。如果我没理解错的话,下面是两种最流行的方法。但是我不明白它们之间有什么不同。这些方法给出了完全相同的结果。如果它们相同,那么为什么会有两种不同的方式?

V1

function Country(name){
this.name=name;
this.cities=[];
this.continent;
}

Country.prototype={
constructor:Country,
addCity:function(name){
this.cities.push(name)
},
setContinent:function(continent){
this.continent=continent;
}
}

V2

function Country(name){
this.name=name;
this.cities=[];
this.continent;

this.addCity=function(name){
this.cities.push(name);
}

this.setContinent=function(continent){
this.continent=continent;
}
}

感谢您的四个很好的回答。我正确理解了区别。您可能知道,从 EcmaScript6 开始,就可以像在 Java 中一样创建类和对象。

添加

那么这个系统和原型(prototype)法是一样的,使用起来没有缺点。

class Country
{

constructor(name){
this.name=name;
this.cities=[];
this.continent;
}

addCity(name){
this.cities.push(name);
}

setContinent(continent){
this.continent=continent;
}
}

c1 = new Country()
c2 = new Country()
console.log(c1.addCity == c2.addCity) // gives true

我试过@vothaison 的方法,正如我所说,我猜这与原型(prototype)方法相同。

最佳答案

你的两种方式不一样,V1是要走的路。

在 V1 中,所有新创建的 Country 实例都将使用相同的 addCity 方法和 setContinent 方法实例。

而在 V2 中,所有实例都有自己的 addCity 方法和 setContinent 方法实例,这是一种资源浪费。

你用这段代码测试它们:

c1 = new Country()
c2 = new Country()
c1.addCity == c2.addCity // true in V1, false in V2

关于javascript - JavaScript 对象创建方法有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41360080/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com