js面向对象实现计数器
使用构造函数实现计数器
通过构造函数创建一个计数器对象,包含计数属性和增减方法:
function Counter() {
this.count = 0;
this.increment = function() {
this.count++;
};
this.decrement = function() {
this.count--;
};
this.getValue = function() {
return this.count;
};
}
const counter = new Counter();
counter.increment();
console.log(counter.getValue()); // 输出1
使用ES6类实现计数器
采用class语法糖实现更简洁的计数器类:

class Counter {
constructor() {
this.count = 0;
}
increment() {
this.count += 1;
}
decrement() {
this.count -= 1;
}
getValue() {
return this.count;
}
}
const counter = new Counter();
counter.increment();
counter.increment();
console.log(counter.getValue()); // 输出2
使用闭包实现私有计数器
通过IIFE和闭包实现带私有变量的计数器:

const Counter = (function() {
let count = 0;
return {
increment: function() {
count++;
},
decrement: function() {
count--;
},
getValue: function() {
return count;
}
};
})();
Counter.increment();
console.log(Counter.getValue()); // 输出1
带步长的计数器实现
扩展计数器功能,支持自定义步长:
class StepCounter {
constructor(step = 1) {
this.count = 0;
this.step = step;
}
increment() {
this.count += this.step;
}
decrement() {
this.count -= this.step;
}
setStep(newStep) {
this.step = newStep;
}
}
const counter = new StepCounter(2);
counter.increment();
console.log(counter.count); // 输出2
使用原型链共享方法
通过原型链实现方法共享,节省内存:
function Counter() {
this.count = 0;
}
Counter.prototype.increment = function() {
this.count++;
};
Counter.prototype.decrement = function() {
this.count--;
};
const c1 = new Counter();
const c2 = new Counter();
c1.increment();
console.log(c1.count); // 输出1
console.log(c2.count); // 输出0




