JavaScript对象创建方法之间有什么区别?

4

我一直在努力更深入地学习JavaScript中的面向对象编程。在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一样创建类和对象。

补充说明

然后,这个系统与原型方法是相同的,使用上没有任何缺点。

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的方法,就像我说的一样,我猜这与原型方法相同。

MDN使用第一种方法:https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/create - ppasler
@charty 虽然你的ES6类看起来像是V2,但内部更接近于V1。 - vothaison
1
我认为我不需要更新答案。这是一个很好的解释:https://reinteractive.com/posts/235-es6-classes-and-javascript-prototypes;请查看一下。 - vothaison
2个回答

6

你的两种方式是不同的,V1 是更好的选择。

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

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

你可以使用以下代码进行测试:

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

我更新了我的问题。你能看一下吗? - amone

1

V1是推荐的方式。

它使用原型模式

原型模式创建新对象,但不是创建未初始化的对象,而是返回用从原型或示例对象复制的值初始化的对象。原型模式也称为属性模式。

MDN很好地解释了优缺点:继承和原型链


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接