ECMAScript2015类与Object.create、new和Object.setPrototypeOf的比较

3
随着ES6的出现,我们有了一种新的创建对象的方式。我的问题是现在应该如何创建对象?假设new操作符的工作方式如下:
function createNewObject(parentFunction){
    var obj = {};
    Object.setPrototypeOf(obj, parentFunction.prototype);
    return parentFunction.apply(obj, Array.prototype.slice.call(arguments,1)) || obj;
}

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

1个回答

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类,它看起来应该像这样:Animal.prototype.name = function(name) { this.name = name; };
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);
}

5
问题还涉及到Object.create和Object.setPrototypeOf之间的区别,但答案甚至没有提到Object.setPrototypeOf。无法理解为什么该答案被选中。 - Maulik Shah
摘自 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/setPrototypeOf: "Object.setPrototypeOf() 方法将一个指定对象的原型(即内部 [[Prototype]] 属性)设置为另一个对象或 null。" - Thomas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接