let p1 = new Point(1, 2); let p2 = new Point(4, 5); console.log('p1.constructor === p2.constructor: ', p1.constructor === p2.constructor);
// 类内部可以使用 get 和 set 关键字,对某个属性设置存值和取值函数,拦截该属性的存取行为 classMyClass{ get prop () { return'getter'; } set prop (value) { console.log('setter: ', value); } } let inst = new MyClass(); inst.prop = 3; console.log('inst.prop: ', inst.prop);
// 存值函数和取值函数时定义在 html 属性的描述对象上面 classCustomHTMLElement{ constructor (element) { this.element = element } get html () { this.element.innerHTML; } set html (value) { this.element.innerHTML = value; } } let descriptor = Object.getOwnPropertyDescriptor(CustomHTMLElement.prototype, 'html'); console.log('"get" in descriptor: ', 'get'in descriptor);
get value () { console.log('Getting the current value!'); returnthis._count; } increment () { this._count++; } } const increasingCounter = new IncreasingCounter(); console.log('increasingCounter.value: ', increasingCounter.value);
// 如果构造函数不是通过 new 命令或 Reflect.construct() 调用,new.target 会返回 undefined /* function Person (name) { if (new.target === Person) { this.name = name; } else { throw new Error('必须使用 new 命令生成实例'); } } const person = new Person('joy'); const notAPerson = Person.call(person, 'joy'); */