Javascript 用prototype扩展角速度控制器
我有以下代码Javascript 用prototype扩展角速度控制器,javascript,angularjs,Javascript,Angularjs,我有以下代码 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 eith
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函数,所以我希望两者都继承自一个公共原型。然而,当我尝试plunker时,它似乎不起作用
在JS中处理这类事情的正确方法是什么?这是一个TypeScript示例
打字稿:
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,请在plunker中使用smth,如,您有
函数时间框
,但在prototype中,请尝试分配TestController.prototype=new Test()
Thank updated仍然有相同的问题如果您在app.js
文件中定义所有函数,或者在index.html
中添加对test.js
的引用,如果您想在index.html
页面中使用test.js
中的代码-您需要添加对该脚本文件的引用,如
:-)只需在app.js
之前包含test.js
)我会看看你贴了什么,等我有机会消化后再检查谢谢!