【问题标题】:Are class, object, and constructor function equivalent?类、对象和构造函数是否等效?
【发布时间】:2017-09-05 06:49:54
【问题描述】:

既然JS有class,我想知道这3个“站”之间是否有区别。有相同/等效的吗? 在所有情况下,我都可以使用station.label 访问标签

//1
export class Station {

    public label: string;
    public code: number;

    constructor(label, code) {
        this.code = code;
        this.label = label;
    }
}
let station = new Station("my label", "my code");

//2    
function Station(label, code) {
    this.label = label;
    this.code = code;
}
let station = new Station("my label", "my code");

// 3
let station = { label: "my label", "code": my code }

【问题讨论】:

    标签: function class object properties ecmascript-6


    【解决方案1】:

    可以这样说:在所有情况下,您都会得到一个带有标签和代码属性的新对象;)

    最终类被转译成函数:

    class A { 
        ...
    }
    

    被转译成类似的东西:

    var A = function A() { 
        _classCallCheck(this, A);
    };
    

    所以你得到了等价的回报,但是如何创建实例会有所不同;)

    例如
    示例 1 和 2 -> new Station()
    示例 3 -> Object.create(Station.prototype)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-17
      • 2017-01-13
      • 2019-01-17
      • 2013-10-14
      • 2010-09-15
      • 1970-01-01
      相关资源
      最近更新 更多