【发布时间】:2014-04-21 00:09:15
【问题描述】:
我有 C# 背景,我开始探索 Angular JS。我的工厂类/对象基于这篇文章:https://medium.com/opinionated-angularjs/2e6a067c73bc
所以我有 2 个工厂类,但我想在另一个工厂中引用一个工厂的实例。但是,由于 java 脚本不是一种类型化的语言,一个工厂的属性和方法在“编译”时在另一个工厂内是不可用的。
检查这个小提琴:http://jsfiddle.net/Frinkahedron/PxdSP/1337/ var myApp = angular.module('myApp', []);
myApp.factory('grid', function () {
// Constructor, with parameters
function grid(sizeX, sizeY, gridName) {
//public properties
this.cells = new Array();
this.name = gridName;
//load cells
var numCells = sizeX * sizeY;
for (var i = 0; i < numCells; i++) {
this.cells.push(i);
}
}
//Return the constructor function
return grid;
});
myApp.factory('game', ['grid', function (_grid_) {
//private reference for the grid factory
var grid = _grid_;
function game(){
//do some setup with grid reference
this.gridName = "Grid : " + grid.gridName;
};
game.prototype.isWinner = function () {
//iterate cells to see if game has been won
//this loop doesn't cause "compile" errors
for (var c in grid.cells){
//do something with each cell in the grid
}
//this loop doesn't work due to grid.cells.length
//because there is no length property of undefined
//uncomment to see it blow up
//for(var i=0; i< grid.cells.length;i++){}
return true;
};
return game;
}]);
function MyCtrl($scope, grid, game) {
var g = new grid(3, 3, "Test Grid");
$scope.myLength = g.cells.length;
$scope.myGridName = g.name;
//how to pass the grid reference to the game?
//if i pass the grid in the constructor of the game,
//it still doesn't work because javascript doesn't have types
//and the grid.cells (and other grid property references) are
//problematic
var a = new game();
$scope.myGameName = a.gridName;
$scope.myWinner = a.isWinner();
}
网格工厂按预期工作,但我不知道如何在游戏工厂中引用网格实例。我尝试将网格“对象”传递给 Game 构造函数,但由于 java 脚本不是类型化语言,因此网格属性/方法在 Game 工厂中未定义。
【问题讨论】:
标签: javascript angularjs