很明显,类属性可以拥有自己的get
和set
函数。但是this
怎么样?
正如我到目前为止所做的那样,合法做这样的事情:
class Bind {
constructor(val) {
this.val = val;
}
set this(val) {
alert('not sure what happens here!');
}
get this() {
return this.val;
}
}
所以这些行:
var b = new Bind(123);
b = 456;
应该调用setter函数,但警报永远不会触发。
知道那个二传手做什么吗?
b = 456;
因为这不会以任何方式更改b
的先前值,它只是将先前存储的引用更改为值。我的意思的一个小例子:
let a = {it: "wont change" };
let b = a;
console.log(a, b);
b = 456;
console.log(a, b);
如果重写b
会以任何方式改变引用的对象,a
也会改变。
相反,您可以通过以下方式联系到setter:
b.this = 456;
class Person {
constructor(name) {
this._name = name;
}
get name() {
console.log("getter")
return this._name.toUpperCase();
}
set name(newName) {
console.log("setter")
this._name = newName;
}
}
let bob = new Person('Bob');
console.log(bob.name);// Outputs 'BOB'
bob.name = "new Bob"
console.log(bob.name); // Outputs 'NEW BOB'