我有以下代码......
var app = angular.module('plunker', []);
TestController = function ($scope, $interval) {
$scope.test = this;
$scope.name = 'World';
this.init();
$interval(function () {
//Added this because we shouldn't update until we either get the user data or that request fails
$scope.test.init();
}, 500);
};
TestController.prototype.init = function () {
console.log("Test this thing");
};
app.controller('MainCtrl', TestController);
这很好但现在我需要在另一个控制器中包含init函数,所以我希望两者都从一个普通的原型继承。但是,当我尝试使用this plunker时,它似乎无法正常工作。
在JS中处理这类事情的正确方法是什么?
答案 0 :(得分:2)
是TypeScript示例http://plnkr.co/edit/HOeJ7nkkp2qRl53zEvVj?p=preview
打字稿:
class Controller {
static $inject = ['$scope']; // deps
constructor($scope) {
$scope.vm = this;
}
value(): string {
return '123';
}
}
class NewController extends Controller {
constructor($scope) {
super($scope);
}
value(): string {
return super.value() + '456';
}
}
declare var angular: any;
angular.module('my', []).controller('controller', NewController);
在JavaScript中看起来像:
//Compiled TypeScript
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
}
var Controller = (function () {
function Controller($scope) {
$scope.vm = this;
}
Controller.$inject = [
'$scope'
];
Controller.prototype.value = function () {
return '123';
};
return Controller;
})();
var NewController = (function (_super) {
__extends(NewController, _super);
function NewController($scope) {
_super.call(this, $scope);
}
NewController.prototype.value = function () {
return _super.prototype.value.call(this) + '456';
};
return NewController;
})(Controller);
angular.module('my', []).controller('controller', NewController);
如果您在JavaScript中需要OOP,请使用http://prototypejs.org/
之类的smth