class Test {
static hehe() {
}
}
Test.hehe()
//(new Test()).hehe()
想问一下这是为什么要这样设计?
class Test {
static hehe() {
}
}
Test.hehe()
//(new Test()).hehe()
想问一下这是为什么要这样设计?
|
flowfireJun 20, 2018 via iPhone
1
难道不是所有语言都这样么,一脸懵逼
|
|
azh7138mJun 20, 2018
3
如果我们只说如何调用的话
const test = new Test(); test.constructor.hehe(); 就可以了, 如果你要问为什么是这样处理的话,我还没找到合理的解释 |
|
nealv2exJun 20, 2018
4
实例方法和静态方法,楼主搞清楚这 2 个东西的概念和区别应该就没有这个问题了
|
|
zsdroidJun 20, 2018
5
不忍直视
|
|
kimownJun 20, 2018 via Android
6
你可以看下 babel transform 后的代码,class Test 其实是语法糖,最终是由 function Test 实现的,static 只把 hehe 作为一个属性添加到 function Test 上,并没有把 hehe 绑定在 function Test 里面作为 this.hehe
|
|
loy6491Jun 20, 2018
7
ES 几都一样
function Test () {} Test.hehe = function () {} Test.prototype.xixi = function () {} ✔️ Test.hehe(); ✔️ (new Test()).xixi() |
|
lancelockJun 21, 2018
8
不这样要 static 干嘛?
|
|
yamedieJun 21, 2018 via Android
9
static 是供 class 中其他暴露在外的方法调用的,是内部方法,本身不对外暴露,就是这样设计的吧
|
|
SilentDepthJun 21, 2018
10
楼上几位大概没理解楼主的问题。楼主问的是:静态方法被设计为不能被实例直接调用,这个设计的动机是什么?
class A {static test() {console.log(1)}} (new A()).test() 如上述代码,为什么 A 的实例在内部未定义 test 方法时不能自动调用类甚至父类的静态方法? |
|
AlloVinceJun 21, 2018
11
```
class A {static test() {console.log(1)}} class B extends A {static test() {console.log(1)}} let ins = new B(); ins.test(); //class A or class B ``` js 没有 java 的强制类型转换,那么如果父类和子类同时定义同名静态方法,实例调用的时候无法区分到底是调用父类还是子类的 |