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

时间:2017-03-14 09:00:58

标签: 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;
}

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

1 个答案:

答案 0 :(得分:5)

使用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);
}
相关问题