Javascript ECMAScript2015类vs Object.create vs new vs Object.setPrototypeOf
随着ES6的出现,我们获得了一种创建对象的新方法。我的问题是我们现在应该如何创建对象? 假设新的操作员是这样工作的Javascript ECMAScript2015类vs Object.create vs new vs Object.setPrototypeOf,javascript,ecmascript-6,es6-class,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,
function createNewObject(parentFunction){
var obj = {};
Object.setPrototypeOf(obj, parentFunction.prototype);
return parentFunction.apply(obj, Array.prototype.slice.call(arguments,1)) || obj;
}
但当类被创建时,到底发生了什么呢?当前在es6中创建对象的“正确”方式是什么?使用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);
}
}
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);
}
如果要创建类型为Cat
的对象,我们将执行以下操作:
let cat1 = new Cat('Felix');
cat1.saySomething(); //Outputs 'meow, my name is Felix'
es6类的特性是语法上的糖分,而不是原型方法。如果我们使用常规原型方法创建Animal
类,它将如下所示:
class Cat extends Animal {
constructor(name){
super(name);
}
saySomething(){
console.log('Meow, my name is ' + this.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);
}
子类将如下所示:
class Cat extends Animal {
constructor(name){
super(name);
}
saySomething(){
console.log('Meow, my name is ' + this.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);
}
这个问题还讨论了Object.create和Object.setPrototypeOf之间的区别。但答案甚至没有提到Object.setPrototypeOf。无法理解如何选择答案。引用自Object。setPrototypeOf()方法将指定对象的原型(即内部[[prototype]]属性)设置为另一个对象或null。“