(六十四)ES6新特征 - Class
1:基本概念
function Position(x, y) {
this.x = x;
this.y = y;
}
const position = new Position(1, 1);
class Position {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
Position === Position.prototype.constructor;
/* true */
const position = new Position(1, 1);
class Position {
constructor(x, y) {
this.x = x;
this.y = y;
}
scan() {
console.log(this.x, this.y);
}
}
Position.prototype;
/*
{
constructor: class Position
scan: ƒ scan()
__proto__: Object
}
*/
class Position {
constructor(x, y) {
this.x = x;
this.y = y;
}
scan() {
console.log(this.x, this.y);
}
}
Object.keys(Position.prototype);
/* [] */
Object.getOwnPropertyNames(Position.prototype);
/* ["constructor", "scan"] */
class Position {
constructor(x, y) {
this.x = x;
this.y = y;
}
scan() {
console.log(this.x, this.y);
}
}
const position = new Position(1, 1);
const { scan } = position;
scan();
/* Cannot read property 'x' of undefined */
class Position {
constructor(x, y) {
this.x = x;
this.y = y;
this.scan = this.scan.bind(this);
}
scan() {
console.log(this.x, this.y);
}
}
const position = new Position(1, 1);
const { scan } = position;
scan();
/* 1 1 */
class Position {
constructor(x, y) {
this.x = x;
this.y = y;
}
scan = () => {
console.log(this.x, this.y);
}
}
const position = new Position(1, 1);
const { scan } = position;
scan();
/* 1 1 */