请求用new/ES6 class重构Object.create的JS代码,探究行为委托效率差异
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

