getter
and setter
are cool.
you can call the function
()
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
()
.
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 ]