簡體   English   中英

JS:如何制作嵌套函數?

[英]JS: How to make nested functions?

我想在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();

當然不是用代碼來使汽車移動等等,而只是一個示例,說明了我如何做到這一點,因此我可以用

function.functionInside.anotherFunction();

提前致謝!

我建議研究一下類,然后可以在主對象內部包含對象,並可以在其上調用函數。 即)存儲在汽車對象內部的馬達對象。

編輯:

這是您所想的最簡單的例子。

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

alert(car.motor.start());

這是我的設置方法:

 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(); 

輸出:

motor started!
motor moved to (0, 0)
window opened

這是一本好書。 ECMA 6支持類,因此將來會更容易。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM