JS:如何制作嵌套函数?

时间:2015-11-09 19:56:15

标签: javascript function

我想在JS中创建一个函数,其中包含函数,并在该函数中创建另一个函数或变量。例如,对于汽车,我想这样称呼:

var car1 = new car("blue");
var curPosX = car1.position.x;
var curPosY = car1.position.y;

var car2 = new car("red");
car2.motor.start();
car2.motor.moveTo(curPosX, curPosY);
car2.color = "red";
car2.window[0].open();

的cource没有代码使汽车移动所以,但只是一个例子我怎么能做到这一点,所以我可以用

来调用它
function.functionInside.anotherFunction();

提前致谢!

2 个答案:

答案 0 :(得分:0)

我建议您查看课程,然后您可以在主要对象中包含对象,您可以在其中调用您的函数。 ie)存储在汽车对象内部的电机对象。

编辑:

以下是您正在考虑的最简单的示例。

var car = {
    motor: {
        start: function () { return "started motor";}
    }
};

alert(car.motor.start());

答案 1 :(得分:0)

以下是我如何设置它:

ERROR | [iOS] unknown: Encountered an unknown error (An unexpected version directory `Private pod subdirectory` was encountered for the `/Users/username/.cocoapods/repos/test/test` Pod in the `test` repository.) during validation.

输出:

var motor = function() {
  this.posX = 0;
  this.posY = 0;
};

motor.prototype.start = function() {
  console.log("motor started!");
};

motor.prototype.moveTo = function(x, y) {
  this.posX = x;
  this.posY = y;
  console.log("motor moved to (" + x + ", " + y + ")");
};

var windowC = function() {
  this.state = false; //closed
};

windowC.prototype.open = function() {
  this.state = true;
  console.log("window opened");
};

var car = function(color) {
  this.color = color;
  this.position = {
    x: 0,
    y: 0
  };
  this.motor = new motor();
  this.window = [new windowC(), new windowC(), new windowC(), new windowC()];
};

var car1 = new car("blue");
var curPosX = car1.position.x;
var curPosY = car1.position.y;

var car2 = new car("red");
car2.motor.start();
car2.motor.moveTo(curPosX, curPosY);
car2.color = "red";
car2.window[0].open();

Here's好读。 ECMA 6支持类,因此将来会更容易。