有些属性或方法,不应该被除了类自身以外访问。这种就被称为被称为私有属性或方法。

传统的写法

在编程领域有一个约定俗成的写法,那就是私有属性或方法以下划线 _ 开头。

这只是一个约定俗成的写法,需要程序员自觉遵守,但仍然可以从外部访问的。

<button id="secondBtn">经过了?秒</button>
<button id="minuteBtn">经过了?分</button>
<button id="resetBtn">重置</button>
<script>
    class Clock {
        _start = 0
        constructor() {
            this._start = Date.now()
        }

        reset() {
            this._start = Date.now()
        }

        get second() {
            return Math.floor((Date.now() - this._start) / 1000)
        }

        get minute() {
            return Math.floor((Date.now() - this._start) / 60 / 1000)
        }
    }

    const clock = new Clock()

    secondBtn.onclick = function () {
        alert(`经过了${clock.second}秒`)
    }

    minuteBtn.onclick = function () {
        alert(`经过了${clock.minute}分`)
    }

    resetBtn.onclick = function () {
        // clock._start = Date.now() // 可以但不推荐
        clock.reset()
    }
</script>

以#开头的语法

在以下实例中, # 开头的变量不能在外部访问。

<button id="secondBtn">经过了?秒</button>
<button id="minuteBtn">经过了?分</button>
<button id="resetBtn">重置</button>
<script>
    class Clock {
        #start = 0
        constructor() {
            this.#start = Date.now()
        }

        reset() {
            this.#start = Date.now()
        }

        get second() {
            return Math.floor((Date.now() - this.#start) / 1000)
        }

        get minute() {
            return Math.floor((Date.now() - this.#start) / 60 / 1000)
        }
    }

    const clock = new Clock()

    secondBtn.onclick = function () {
        alert(`经过了${clock.second}秒`)
    }

    minuteBtn.onclick = function () {
        alert(`经过了${clock.minute}分`)
    }

    resetBtn.onclick = function () {
        // clock.#start = Date.now() // 报错
        clock.reset()
    }
</script>

$$demo

<button id="secondBtn">经过了?秒</button> <button id="minuteBtn">经过了?分</button> <button id="resetBtn">重置</button> <script> class Clock { #start = 0 constructor() { this.#start = Date.now() }

    reset() {
        this.#start = Date.now()
    }

    get second() {
        return Math.floor((Date.now() - this.#start) / 1000)
    }

    get minute() {
        return Math.floor((Date.now() - this.#start) / 60 / 1000)
    }
}

const clock = new Clock()

secondBtn.onclick = function () {
    alert(`经过了${clock.second}秒`)
}

minuteBtn.onclick = function () {
    alert(`经过了${clock.minute}分`)
}

resetBtn.onclick = function () {
    // clock.#start = Date.now() // 报错
    clock.reset()
}

</script>

$$

$$warning

私有属性或方法不可以被继承。

$$

$$jsdemo$$
$$edit$$
class Animal {
    #family = "动物"
    sayFamily() {
        alert(this.#family) // ok
    }
}

class Cat extends Animal {
    test() {
        alert(this.#family) // 报错
    }
}