我知道有很多OO的JavaScript的问题,这样,我一个一直在阅读了大量的资源....但它仍然是迄今为止我最长篇大论的学习曲线为止!
我不是训练有素的古典遗憾,所以我将不得不只显示你们在C#中的什么,我想acheive的例子。
我希望你能帮助!
public class Engine
{
public int EngineSize;
public Engine()
{
}
}
public class Car
{
public Engine engine;
public Car()
{
engine = new Engine();
}
}
大家好我不是真的担心私人/公共及以上C#示例的命名约定。
所有我想知道的是如何复制在Javascript这种结构?
谢谢!
function Engine(size) {
var privateVar;
function privateMethod () {
//...
}
this.publicMethod = function () {
// with access to private variables and methods
};
this.engineSize = size; // public 'field'
}
function Car() { // generic car
this.engine = new Engine();
}
function BMW1800 () {
this.engine = new Engine(1800);
}
BMW1800.prototype = new Car(); // inherit from Car
var myCar = new BMW1800();
所以,你真的只是想知道一个对象如何能够包含另一个? 这里是一个非常简单的采样的转换:
function Engine()
{
this.EngineSize=1600;
}
function Car()
{
this.engine=new Engine();
}
var myCar=new Car();
function Engine(){ // this is constructor. Empty since Engine do nothing.
}
Engine.prototype.EngineSize=null; // this is public property
function Car(){ // this is Car constructor. It initializes Engine instance and stores it in Engine public property
this.Engine =new Engine();
}
Car.prototype.Engine =null;
当你将新车实例。 汽车构造函数将创建引擎的新实例,并将其分配给汽车实例的发动机性能。
文章来源: Object Oriented Javascript - How To Define A Class Within A Class? from a C# example