如何在Java Script中定义嵌套类.
这是我的代码片段:
objA = new TestA(); function TestB () { this.testPrint = function () { print ( " Inside testPrint " ); } } function TestA () { var myObjB = new TestB(); }
现在我尝试使用objA访问testPrint
objA.myObjB.testPrint();
但它给出错误"objA没有属性"
如何使用objA处理程序访问testB方法?
如果您希望无法从外部类外部访问内部嵌套类的原型定义,以及更清晰的OO实现,请查看此内容.
var BobsGarage = BobsGarage || {}; // namespace /** * BobsGarage.Car * @constructor * @returns {BobsGarage.Car} */ BobsGarage.Car = function() { /** * Engine * @constructor * @returns {Engine} */ var Engine = function() { // definition of an engine }; Engine.prototype.constructor = Engine; Engine.prototype.start = function() { console.log('start engine'); }; /** * Tank * @constructor * @returns {Tank} */ var Tank = function() { // definition of a tank }; Tank.prototype.constructor = Tank; Tank.prototype.fill = function() { console.log('fill tank'); }; this.engine = new Engine(); this.tank = new Tank(); }; BobsGarage.Car.prototype.constructor = BobsGarage.Car; /** * BobsGarage.Ferrari * Derived from BobsGarage.Car * @constructor * @returns {BobsGarage.Ferrari} */ BobsGarage.Ferrari = function() { BobsGarage.Car.call(this); }; BobsGarage.Ferrari.prototype = Object.create(BobsGarage.Car.prototype); BobsGarage.Ferrari.prototype.constructor = BobsGarage.Ferrari; BobsGarage.Ferrari.prototype.speedUp = function() { console.log('speed up'); }; // Test it on the road var car = new BobsGarage.Car(); car.tank.fill(); car.engine.start(); var ferrari = new BobsGarage.Ferrari(); ferrari.tank.fill(); ferrari.engine.start(); ferrari.speedUp(); // var engine = new Engine(); // ReferenceError console.log(ferrari);
这样,您可以拥有原型继承和嵌套类,以便BobsGarage.Car
在构造函数之外无法访问其中定义的类,BobsGarage.Car
但派生类可以访问它们的实例,如测试代码中所示.
注意:我指的是MDN中定义的Javascript中的Class概念.
使用this.myObjB而不是var myObjB