class讲解之5 静态方法
2020-08-07 本文已影响0人
zhang463291046
以下内容是引用或者借鉴别人的,自己只是做个笔记,方便学习。理解错误的地方,欢迎评论。如有侵权,私聊我删除,未经允许,不准作为商业用途
在一个方法前,加上static
关键字,这就称为“静态方法”。该方法是直接通过类来调用,不会被实例继承
class Foo {
static classMethod() {
return 'hello';
}
}
Foo.classMethod() // 'hello'
var foo = new Foo();
foo.classMethod()
// TypeError: foo.classMethod is not a function

静态方法包含this
关键字,这个this
指的是类,而不是实例
class Foo {
static bar() {
this.baz(); // this指Foo
}
static baz() {
console.log('hello');
}
baz() {
console.log('world');
}
}
Foo.bar() // hello
// 等同
let Foo = function() {};
Foo.bar = function() {
this.baz(); // this指Foo
};
Foo.baz = function() {
console.log("hello");
};
Foo.prototype.baz = function() {
console.log("world");
};
Foo.bar() // hello