JavaScript类设置自己

问题描述 投票:2回答:2

很明显,类属性可以拥有自己的getset函数。但是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函数,但警报永远不会触发。

知道那个二传手做什么吗?

javascript class ecmascript-6 setter es6-class
2个回答
2
投票
  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;

0
投票
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'
© www.soinside.com 2019 - 2024. All rights reserved.