How to add getter and setter to the js built-in object constructor

The calling methods of

getter and setter are cool.
you can call the function

without writing () to execute parentheses.

when we create an object constructor Person :

function Person(value) {
    this.counter = value;
}

We can add a getter or setter method to the object constructor Person :

Person.prototype = {
    get increment () {
        this.counterPP;
    }
}

so that when we new Person , we can call increment

without executing () .
var person = new Person(3)
person.increment
console.log(person.counter) // 4

question:

In the same way, when we new an array, we add a getter

to the array in the same way.
Array.prototype = {
    get increment() {
        this[0]PP;
    }
}

var arr = new Array(1,3);
arr.increment
console.log(arr)  // Array(2)[ 1,3 ]

the grammar didn"t make a mistake, but it didn"t work.
I wonder why?

but when you write it as a method, it"s actually effective

.
Array.prototype.increment = function() {
        this[1]PP;
    }


var arr = new Array(1,3);
arr.increment()
console.log(arr)  // Array(2)[ 1,4 ]
Aug.02,2021

Array.prototype = {
    get increment() {
        this[0]PP;
    }
}

this is a direct modification of Array.prototype to another object. If the push of the array is modified successfully, it can be considered not an array without it, so it is not allowed to be modified. You can try to modify it in strict mode.
you can modify it in this way

.
Object.defineProperty(Array.prototype,'increment',{
        get(){
            return this[0]PP;
        }
    })
    var arr=[1,2,3];
    arr.increment;
    console.log(arr);
    arr.increment;
    console.log(arr);
Menu