当前位置:首页 > JavaScript

js面向对象实现计数器

2026-01-31 11:14:18JavaScript

使用构造函数实现计数器

通过构造函数创建一个计数器对象,包含计数属性和增减方法:

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语法糖实现更简洁的计数器类:

js面向对象实现计数器

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和闭包实现带私有变量的计数器:

js面向对象实现计数器

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

分享给朋友:

相关文章

vue实现计数器

vue实现计数器

vue实现计数器 使用选项式API实现 在Vue的选项式API中,可以通过data定义计数器变量,并在methods中定义增减方法: <template> <div>…

js实现一个面向对象

js实现一个面向对象

面向对象编程基础 面向对象编程(OOP)的核心概念包括封装、继承和多态。JavaScript 通过构造函数、原型链和 ES6 的 class 语法支持 OOP。 使用构造函数实现 通过构造函数定义对…

vue实现计数器

vue实现计数器

Vue 实现计数器的方法 使用 Vue 2 实现计数器 在 Vue 2 中,可以通过 data 属性定义计数器变量,并在方法中实现增减逻辑。 <template> <div&g…

js面向对象的实现

js面向对象的实现

JavaScript 面向对象实现方式 JavaScript 是一种基于原型的面向对象语言,与传统的基于类的语言(如 Java、C++)不同。以下是 JavaScript 中实现面向对象编程的几种主要…

js面向对象实现时钟

js面向对象实现时钟

面向对象实现时钟的方法 使用JavaScript的面向对象编程(OOP)可以实现一个动态更新的时钟。以下是具体实现步骤: 定义Clock类 创建一个Clock类,用于封装时钟的逻辑和数据: cla…

如何面向对象写java

如何面向对象写java

面向对象编程基础 面向对象编程(OOP)是一种以对象为核心的编程范式,Java 是完全面向对象的语言。核心概念包括封装、继承、多态和抽象。 类(Class):对象的模板,定义属性和方法。例如:…