为什么不能覆盖静态方法?
如果可能,请举例说明.
试图绕过Javascript对OO的看法......和许多其他人一样,对constructor财产产生混淆.特别是constructor财产的重要性,因为我似乎无法使其产生任何影响.例如:
function Foo(age) {
this.age = age;
}
function Bar() {
Foo.call(this, 42);
this.name = "baz";
}
Bar.prototype = Object.create(Foo.prototype);
var b = new Bar;
alert(b.constructor); // "Foo". That's OK because we inherit `Foo`'s prototype.
alert(b.name); // "baz". Shows that Bar() was called as constructor.
alert(b.age); // "42", inherited from `Foo`.
Run Code Online (Sandbox Code Playgroud)
在上面的例子中,对象b似乎有正确的构造函数call(Bar) - 并且它继承了age属性Foo.那么为什么许多人认为这是必要的步骤:
Bar.prototype.constructor = Bar;
Run Code Online (Sandbox Code Playgroud)
显然,Bar构造时会调用正确的构造函数b,因此这个原型属性有什么影响?我很想知道它实际上使构造函数属性设置'正确'有什么实际区别 - 因为我无法看到它对创建对象后实际调用的构造函数有任何影响.
我有这个类对静态方法进行内部调用:
export class GeneralHelper extends BaseHelper{
static is(env){
return config.get('env:name') === env;
}
static isProd(){
return GeneralHelper.is('prod');
}
}
Run Code Online (Sandbox Code Playgroud)
我可以使用任何关键字来替换下面一行中的类名:
GeneralHelper.is('prod');
Run Code Online (Sandbox Code Playgroud)
在PHP中也有self,static等ES6是否提供类似这些东西吗?
TY.
似乎可以在构造函数中嵌套一个类,然后可以从类中的任何地方实例化,这是官方的吗?
[编辑]例如,
class C {
constructor() {
class D {
constructor() { }
}
}
method() {
var a = new D(); // works fine
}
}
//var a = new D(); // fails in outer scope
Run Code Online (Sandbox Code Playgroud)
traceur生成了JS https://google.github.io/traceur-compiler/demo/repl.html
$traceurRuntime.ModuleStore.getAnonymousModule(function() {
"use strict";
var C = function C() {
var D = function D() {};
($traceurRuntime.createClass)(D, {}, {});
};
($traceurRuntime.createClass)(C, {method: function() {
var a = new D();
}}, {});
return {};
});
//# sourceURL=traceured.js
Run Code Online (Sandbox Code Playgroud) 如何从实现该getter的类的实例访问静态getter?
例如,我有这个类:
class Component {
static get isComponent() { return true; }
constructor() {}
}
const c = new Component();
Run Code Online (Sandbox Code Playgroud)
我如何从"组件"类的"c""isComponent"调用?我四处读书,我发现的就是这样的:
Object.getPrototypeOf(c).isComponent
Run Code Online (Sandbox Code Playgroud)
但这不适用于我的情况,因为Component原型对象中没有"isComponent"方法.如果我像这样编写类,上面的代码可以工作:
Component.prototype.isComponent = () => { return true; }
Run Code Online (Sandbox Code Playgroud)
但这不是我想写课的方式.我错过了什么?TNX
当我试图在javascript中从构造函数调用静态方法时,它表示该方法不存在.
class TestClass {
constructor(){
this.staticMethod();
}
static staticMethod() {
}
}
Run Code Online (Sandbox Code Playgroud)
如果我尝试从构造函数调用普通方法,这工作正常.如果静态方法属于类而不是实例,为什么它不允许它们从构造函数调用?
在ES6中,给出以下示例:
export default class MyStyle extends Stylesheet {
static Color = {
mainDark: '#000'
}
static Comp = {
...
color: Color.mainDark
}
}
Run Code Online (Sandbox Code Playgroud)
如何访问Color.mainDark(静态字段)?
javascript ×6
ecmascript-6 ×4
static ×2
class ×1
constructor ×1
getter ×1
java ×1
oop ×1
overriding ×1
prototype ×1
reactjs ×1
traceur ×1