JavaScript Class 自己设置
JavaScript Class set itself
很明显,class 属性可以拥有自己的 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 函数,但永远不会触发警报。
知道 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'
很明显,class 属性可以拥有自己的 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 函数,但永远不会触发警报。
知道 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'