概述
function Point(x,y){
this.x = x;
this.y = y;
}
Point.prototype.toString = () {
return '(' + this.x + ',' + this.y + ')';
};
//定义类
class Point {
constructor(x,y) {
x;
y;
}
toString() {
;
}
}
class Point {
constructor(){
...
}
toString(){
}
toValue(){
}
}
等同于
Point.prototype = {
toString(){},toValue(){}
};
class B {}
let b = new B();
b.constructor === B.prototype.constructor true
constructor方法
class Foo {
constructor() {
return Object.create(null);
}
}
new Foo() instanceof Foo
false
类的实例对象
报错
var point = Point(2,3);
正确
var point = new Point(2,3);
var p1 = );
var p2 = new Point(3,2);
p1.__proto__.printName = function () { return 'Oops' };
p1.printName() "Oops"
p2.printName() "Oops"
var p3 = new Point(4,1)">);
p3.printName() "Oops"
name属性
class Point {}
Point.name "Point"
Class表达式
const MyClass = class Me {
getClassName() {
return Me.name;
}
};
let inst = MyClass();
inst.getClassName() Me
Me.name ReferenceError: Me is not defined
const MyClass = class { /* ... */ };
let person = class {
constructor(name) {
this.name = name;
}
sayName() {
console.log(this.name);
}
}('张三');
person.sayName(); "张三"
不存在变量提升
new Foo(); ReferenceError
class Foo {}
基本用法
class ColorPoint extends Point {}
class ColorPoint extends Point {
constructor(x,y,color) {
super(x,y); 调用父类的constructor(x,y)
this.color = color;
}
toString() {
return this.color + ' ' + super.toString(); 调用父类的toString()
}
}
class Point { */ }
class ColorPoint extends Point {
constructor() {
}
}
let cp = new ColorPoint(); ReferenceError
类的prototype属性和__proto__属性
class A {
}
class B extends A {
}
B.__proto__ === A true
B.prototype.__proto__ === A.prototype true
class A {
}
class B {
}
B的实例继承A的实例
Object.setPrototypeOf(B.prototype,A.prototype);
B继承A的静态属性
Object.setPrototypeOf(B,A);
Object.getPrototypeOf()
Object.getPrototypeOf(ColorPoint) === Point
true
super关键字
- Boolean()
- Number()
- String()
- Array()
- Date()
- Function()
- RegExp()
- Error()
- Object()
class MyArray extends Array {
constructor(...args) {
super(...args);
}
}
var arr = MyArray();
arr[0] = 12;
arr.length 1
arr.length = 0;
arr[0] undefined
class Foo {
static classMethod() {
return 'hello';
}
}
Foo.classMethod() 'hello'
var foo = Foo();
foo.classMethod()
TypeError: undefined is not a function
;
}
}
class Bar extends Foo {
}
Bar.classMethod(); 'hello'