You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求用new/ES6 class重构Object.create的JS代码,探究行为委托效率差异

Refactoring Kyle Simpson's Behavior Delegation Example to Use new and ES6 class

Hey there! I totally get wanting to verify efficiency claims firsthand while working through YDKJS: this & Object Prototypes—no need to take conclusions on faith. Let's refactor Kyle's original behavior delegation code into both a constructor function (using new) and ES6 class version, so you can run side-by-side tests.

1. Refactored with Constructor Functions (new keyword)

This version builds the same prototype delegation chain using traditional constructor functions:

// Define the base Task constructor and its prototype methods
function Task() {}
Task.prototype.setID = function(ID) {
  this.id = ID;
};
Task.prototype.outputID = function() {
  console.log(this.id);
};

// Define XYZ as a constructor inheriting from Task
function XYZ() {
  Task.call(this); // Call parent constructor (optional here, but good practice)
}
// Set up prototype inheritance: XYZ.prototype delegates to Task.prototype
XYZ.prototype = Object.create(Task.prototype);
XYZ.prototype.constructor = XYZ; // Fix constructor reference

// Add methods to XYZ's prototype
XYZ.prototype.prepareTask = function(ID, Label) {
  this.setID(ID);
  this.label = Label;
};
XYZ.prototype.outputTaskDetails = function() {
  this.outputID();
  console.log(this.label);
};

// Create and use an instance
var myTask = new XYZ();
myTask.prepareTask("myID", "Some Task");
myTask.outputTaskDetails();
console.log(myTask);

2. Refactored with ES6 class Syntax

ES6 classes are just syntactic sugar over prototype-based inheritance—this version does the exact same thing under the hood, but with cleaner, more readable code:

class Task {
  setID(ID) {
    this.id = ID;
  }
  outputID() {
    console.log(this.id);
  }
}

class XYZ extends Task {
  prepareTask(ID, Label) {
    this.setID(ID);
    this.label = Label;
  }
  outputTaskDetails() {
    this.outputID();
    console.log(this.label);
  }
}

// Create and use an instance
const myTask = new XYZ();
myTask.prepareTask("myID", "Some Task");
myTask.outputTaskDetails();
console.log(myTask);

Key Note

Both refactored versions mirror the original code's delegation chain:

  • In the original, myTask → XYZ → Task
  • In the constructor/class versions, myTask → XYZ.prototype → Task.prototype

This means the core functionality is identical, so you can run direct performance comparisons between the Object.create() approach and these new/class variants to test the efficiency claims yourself.

内容的提问来源于stack exchange,提问作者Alon Parag

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:40:30