ECMAScript2015 class vs Object.create vs new vs Object.setPrototypeOf
ECMAScript2015 class vs Object.create vs new vs Object.setPrototypeOf
随着 ES6 的出现,我们有了一种创建对象的新方法。我的问题是我们现在应该如何创建对象?
假设 new 运算符是这样工作的
function createNewObject(parentFunction){
var obj = {};
Object.setPrototypeOf(obj, parentFunction.prototype);
return parentFunction.apply(obj, Array.prototype.slice.call(arguments,1)) || obj;
}
但是创建 class 时到底发生了什么?在 es6 中当前 "proper" 创建对象的方式是什么?
使用 es6,我们将使用以下语法创建一个 class:
class Animal{
constructor(name){
this.name = name;
}
saySomething(){
console.log('Hi, my name is' + this.name);
}
}
如果我们想创建一个名为 Cat
的子 class,它将如下所示:
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 class 特性是原型方法的语法糖。如果我们要使用常规原型方法创建 Animal
class,它将如下所示:
var Animal = function(name){
this.name = name;
}
Animal.prototype.saySomething = function(){
console.log('hi, my name is ' + this.name);
}
子class看起来像这样:
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);
}
随着 ES6 的出现,我们有了一种创建对象的新方法。我的问题是我们现在应该如何创建对象? 假设 new 运算符是这样工作的
function createNewObject(parentFunction){
var obj = {};
Object.setPrototypeOf(obj, parentFunction.prototype);
return parentFunction.apply(obj, Array.prototype.slice.call(arguments,1)) || obj;
}
但是创建 class 时到底发生了什么?在 es6 中当前 "proper" 创建对象的方式是什么?
使用 es6,我们将使用以下语法创建一个 class:
class Animal{
constructor(name){
this.name = name;
}
saySomething(){
console.log('Hi, my name is' + this.name);
}
}
如果我们想创建一个名为 Cat
的子 class,它将如下所示:
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 class 特性是原型方法的语法糖。如果我们要使用常规原型方法创建 Animal
class,它将如下所示:
var Animal = function(name){
this.name = name;
}
Animal.prototype.saySomething = function(){
console.log('hi, my name is ' + this.name);
}
子class看起来像这样:
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);
}