繁体   English   中英

如何在构造函数中访问类变量? (node.js OOP)

[英]How to access class variables in the constructor? (node.js OOP)

有什么方法可以访问构造函数中的类变量?

var Parent = function() {
  console.log(Parent.name);
};
Parent.name = 'parent';

var Child = function() {
  Parent.apply(this, arguments);
}
require('util').inherits(Child, Parent);
Child.name = 'child';

即,父类的构造函数应记录“父”,子类的构造函数应记录“子”,这取决于每个类中的某个类变量。

上面的代码无法正常工作。

在香草js中:

var Parent = function() {
  console.log(this.name);
};
Parent.prototype.name = 'parent';

var Child = function() {
  Parent.apply(this, arguments);
}

Child.prototype = new Parent();
Child.prototype.constructor = Child;
Child.prototype.name = 'child';

var parent = new Parent();
var child = new Child();

utils.inherits只是简化了

Child.prototype = new Parent();
Child.prototype.constructor = Child;

util.inherits(Child, Parent);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM