【问题标题】:ECMAScript2015 class vs Object.create vs new vs Object.setPrototypeOfECMAScript2015 类 vs Object.create vs new vs Object.setPrototypeOf
【发布时间】:2017-03-14 09:00:57
【问题描述】:

随着 ES6 的出现,我们有了一种创建对象的新方法。我的问题是我们现在应该如何创建对象? 假设 new 运算符是这样工作的

function createNewObject(parentFunction){
    var obj = {};
    Object.setPrototypeOf(obj, parentFunction.prototype);
    return parentFunction.apply(obj, Array.prototype.slice.call(arguments,1)) || obj;
}

但是在创建类时到底发生了什么?在 es6 中创建对象的当前“正确”方式是什么?

【问题讨论】:

    标签: javascript ecmascript-6 es6-class


    【解决方案1】:

    使用 es6,我们将使用以下语法创建一个类:

    class Animal{
        constructor(name){
            this.name = name;
        } 
        saySomething(){
            console.log('Hi, my name is' + this.name);
        }
    }
    

    如果我们要创建一个名为Cat 的子类,它看起来像这样:

    class Cat extends Animal {
        constructor(name){
            super(name);
        }   
        saySomething(){
            console.log('Meow, my name is ' + this.name);
        }
    }
    

    如果我们想创建Cat 类型的对象,我们会这样做:

    let cat1 = new Cat('Felix');
    cat1.saySomething(); //Outputs 'meow, my name is Felix'
    

    es6 类特性是原型方法的语法糖。如果我们要使用常规原型方法创建 Animal 类,它看起来像这样:

    var Animal = function(name){
        this.name = name;
    }
    Animal.prototype.saySomething = function(){
       console.log('hi, my name is ' + this.name);
    }
    

    子类看起来像这样:

    var Cat = function(name){
        Animal.call(this, name);
    }
    Cat.prototype = Object.create(Animal.prototype);
    Cat.prototype.saySomething = function(){
      console.log('Meow, my name is ' + this.name);
    }
    

    【讨论】:

    • 该问题还谈到了 Object.create 和 Object.setPrototypeOf 之间的区别。但答案甚至没有提到 Object.setPrototypeOf。无法理解答案是如何被选中的。
    • 引用自developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Object.setPrototypeOf() 方法将指定对象的原型(即内部[[Prototype]]属性)设置为另一个对象或null。"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-29
    • 2010-09-26
    • 2020-10-06
    • 2020-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多