ES6中如何避免使用this引用类的方法与实例变量?
this References in JavaScript Classes Great question! Dealing with repetitive this calls (like this.reduceValue(this.value1 - this.value2)) can make code feel clunky and harder to read. Let's walk through two clean approaches to rewrite your subtractor class so you never need to use this to access value1 or value2.
Option 1: Use Closures in a Class Constructor
By storing your values as local variables in the constructor, you can let class methods access them directly via closures—no this required. This also keeps your values truly private (they can't be modified from outside the class unless you expose a method for it):
const Subtractor = class { constructor(val1, val2) { // Local variables accessible to inner methods via closure let value1 = val1; let value2 = val2; // Define methods directly on the instance to access closure variables this.subtract = function() { value2 -= value1; }; // Optional: Add a getter if you need to retrieve values later this.getCurrentValues = function() { return { value1, value2 }; }; // Example for your `reduceValue` use case const reduceValue = (num) => { // Replace with your actual reduce logic return num * 0.5; }; this.calculateReduced = function() { // No `this` anywhere! Just use the closure variables and function return reduceValue(value1 - value2); }; } }; // Usage const mySub = new Subtractor(3, 10); mySub.subtract(); console.log(mySub.getCurrentValues()); // { value1: 3, value2: 7 } console.log(mySub.calculateReduced()); // -2 (result of (3-7)*0.5)
Option 2: Use a Factory Function (No Class Needed)
If you don't need class-specific features like inheritance, a factory function is even lighter. It returns an object with methods that access private variables via closures, completely ditching this and the class keyword:
function createSubtractor(val1, val2) { let value1 = val1; let value2 = val2; // Define your reduce function here if needed const reduceValue = (num) => num * 0.5; return { subtract: () => { value2 -= value1; }, getCurrentValues: () => ({ value1, value2 }), calculateReduced: () => reduceValue(value1 - value2) }; } // Usage const mySub = createSubtractor(5, 20); mySub.subtract(); console.log(mySub.getCurrentValues()); // { value1: 5, value2: 15 } console.log(mySub.calculateReduced()); // -5 (result of (5-15)*0.5)
Key Takeaway
Both approaches leverage closures to let methods access variables directly without relying on this. This cleans up your code and adds a layer of privacy—your value1 and value2 can't be accidentally modified from outside the class/factory, which is a nice bonus over attaching them to this.
内容的提问来源于stack exchange,提问作者user6369603

