Javascript 从构造函数调用类方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35504605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calling a class method from the constructor
提问by Vivek Kumar
I'm getting an error when calling a class method from its constructor. Is it possible to call a method from the constructor? I tried calling the base class method from the constructor of a derived class but I am still getting an error.
从其构造函数调用类方法时出现错误。是否可以从构造函数调用方法?我尝试从派生类的构造函数调用基类方法,但仍然出现错误。
'use strict';
class Base {
constructor() {
this.val = 10;
init();
}
init() {
console.log('this.val = ' + this.val);
}
};
class Derived extends Base {
constructor() {
super();
}
};
var d = new Derived();
? js_programs node class1.js /media/vi/DATA/programs/web/js/js_programs/class1.js:7 init(); ^
ReferenceError: init is not defined at Derived.Base (/media/vi/DATA/programs/web/js/js_programs/class1.js:7:9) at Derived (/media/vi/DATA/programs/web/js/js_programs/class1.js:18:14) at Object. (/media/vi/DATA/programs/web/js/js_programs/class1.js:23:9) at Module._compile (module.js:435:26) at Object.Module._extensions..js (module.js:442:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:311:12) at Function.Module.runMain (module.js:467:10) at startup (node.js:136:18) at node.js:963:3 ? js_programs
? js_programs 节点 class1.js /media/vi/DATA/programs/web/js/js_programs/class1.js:7 init(); ^
ReferenceError: init is not defined at Derived.Base (/media/vi/DATA/programs/web/js/js_programs/class1.js:7:9) at Derived (/media/vi/DATA/programs/web/js/ js_programs/class1.js:18:14) 在对象。(/media/vi/DATA/programs/web/js/js_programs/class1.js:23:9) at Module._compile (module.js:435:26) at Object.Module._extensions..js (module.js :442:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:311:12) at Function.Module.runMain (module.js:467:10) 启动时(node.js:136:18) 在 node.js:963:3 ?js_programs
回答by deceze
You're calling the functioninit()
, not the methodinit
of either Base
or the current object. No such function exists in the current scope or any parent scopes. You need to refer to your object:
你调用的函数init()
,而不是方法init
的任一Base
或当前对象。当前作用域或任何父作用域中不存在此类函数。您需要引用您的对象:
this.init();
回答by madox2
You are missing this
keyword:
您缺少this
关键字:
this.init();