生成实例对象的传统方法是通过构造函数,下面是一个案例:
function Point(x, y) {
this.x = x
this.y = y
}
Point.prototype.toString = function() {
return '(' + this.x + ', ' + this.y + ')'
}
var p = new Point(1, 2)
弊端:和传统的面向对象语言写法差异很大,容易让刚入门的程序员产生困惑。
ES6 提供了更接近传统语言的写法,引入了 Class(类)这个概念,作为对象的模板。通过class关键字,可以定义类。
实例一:
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
好处:可以让对象原型的写法变得更清晰更像面向对象编程的语法
私有属性
es6不支持私有属性;在属性名之前,使用#
,为class
加了私有属性
this 的指向,类的方法内部如果含有this,它默认指向类的实例。
实例一:
class Logger {
printName(name = 'there') {
this.print(`Hello ${name}`);
}
print(text) {
console.log(text);
}
}
const logger = new Logger();
const { printName } = logger;
printName(); // TypeError: Cannot read property 'print' of undefined
单独使用有可能报错
constructor 方法
它是类的默认方法,一个类必须有constructor方法,如果没有,就会默认添加一个空的constructor方法。
实例一:
class Point {
}
// 等同于
class Point {
constructor() {}
}
他会默认添加一个constructor 方法
css继承
Class 可以通过extends关键字实现继承
class Point {
}
class ColorPoint extends Point {
}
定义的类通过extends关键字,继承了piont所有属性和方法
Object.getPrototypeOf()
Object.getPrototypeOf方法可以用来从子类上获取父类。
Object.getPrototypeOf(ColorPoint) === Point
// true
3super 关键字
super作为函数调用时,代表父类的构造函数
class A {}
class B extends A {
constructor() {
super();
}
}
super作为对象时,在普通方法中,指向父类的原型对象
class A {
p() {
return 2;
}
}
class B extends A {
constructor() {
super();
console.log(super.p()); // 2
}
}
let b = new B();
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。