//传统ES5 class写法
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)
console.log(p.toString())
// ES6写法
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() { //不用写function 直接写名字就可以
return '(' + this.x + ', ' + this.y + ')';
}
sayHello() {
console.log('hello')
}
}
//上面的代码等同于
Point.prototype = {
constructor() { },
toString() { },
sayHello() { },
}
var p = new Point(1, 2) //写给Point的参数会给到constructor
console.log(p.toString())
p.sayHello()
// es5可以获取到point类内部的方法,
var Point = function (x, y) { }
Point.prototype.toString = function () {
console.log('tostring fangfa1')
}
console.log(Object.keys(Point.prototype))
//es6不可获取
class Point {
constructor(x, y) {
this.x = x, this.y = y
}
toString() {
console.log('tostring fangfa1')
}
}
console.log(Object.prototype)
console.log(Object.getOwnPropertyNames(Point.prototype))
// 取值和复制 getter setter
class Myclass {
get class() {
return 'class:' + this.name
}
set class(name) {
this.name = name
}
}
var myclass = new Myclass()
myclass.class = 2034
console.log(myclass.class)
// 静态方法
// 加上static关键字,就表示该方法不会被实例继承,而是直接通过类来调用,
// 如果静态方法包含this关键字,这个this指的是类,而不是实例。
class Foo {
static getFoo() {
this.foo()
}
static foo() {
console.log('hello foo')
}
}
Foo.getFoo()
class bar extends Foo {
// 父类的静态方法,可以被子类继承。
static father() {
return super.getFoo()
//在子类中通过super调用
}
}
bar.getFoo()
bar.father()
//静态属性
//原写法
class Foo {
}
Foo.prop = 1
console.log(Foo.prop)
//新写法
class bar {
static myStaticProp = 42
}
console.log(bar.myStaticProp)
ES6 class 学习笔记
于 2022-02-28 20:35:51 首次发布