ECMAScript2015类vs Object.create vs new vs Object.setPrototypeOf

Ber*_*gan 3 javascript ecmascript-6 es6-class

随着ES6的出现,我们得到了一种创建对象的新方法.我的问题是我们现在应该如何创建对象?假设新运算符的工作原理如下

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

但是在创建课程时究竟发生了什么?在es6中创建对象的当前"正确"方式是什么?

Jac*_*son 5

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

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

如果我们想要创建一个名为的子类Cat,它将如下所示:

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

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

let cat1 = new Cat('Felix');
cat1.saySomething(); //Outputs 'meow, my name is Felix'
Run Code Online (Sandbox Code Playgroud)

es6类特征是原型方法的语法糖.如果我们Animal使用常规原型方法创建类,它将如下所示:

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

子类看起来像这样:

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);
}
Run Code Online (Sandbox Code Playgroud)

  • 该问题还讨论了 Object.create 和 Object.setPrototypeOf 之间的区别。但答案甚至没有提到 Object.setPrototypeOf。无法理解答案是如何被选中的。 (4认同)