如何在构造函数中访问类variables? (node.js OOP)
有没有办法在构造函数中访问类variables?
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';
即父的构造函数应该logging“父”和孩子的构造函数应该logging“孩子”基于每个类中的一个类variables。
上面的代码不能像我所期望的那样工作。
这里是在香草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);