【问题标题】:What is the difference between JavaScript Object creation methods?JavaScript 对象创建方法有什么区别?
【发布时间】:2017-05-12 14:53:36
【问题描述】:

我一直在尝试更深入地学习 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 中一样创建类和对象。

加法

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

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

【问题讨论】:

标签: javascript class oop object


【解决方案1】:

你的两条路不一样,V1是要走的路。

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

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

你用这段代码测试它们:

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

【讨论】:

  • 我更新了我的问题。你能看一下吗?
【解决方案2】:

V1 是推荐的方式。

它使用Prototype Pattern

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

MDN 很好地解释了利弊:Inheritance and the prototype chain

【讨论】:

    猜你喜欢
    • 2013-04-13
    • 1970-01-01
    • 2021-03-25
    • 2011-09-23
    • 1970-01-01
    • 2011-07-20
    • 1970-01-01
    • 2015-02-04
    相关资源
    最近更新 更多