javascript - Angular Controller 继承/覆盖 "superclass"方法

标签 javascript angularjs inheritance

当我以 Angular 扩展 Controller 时,有没有办法从覆盖它的“子类”函数调用“父类(super class)” Controller 上的函数?

为清楚起见——在 Java 中我会这样做:

class Foo {
    void doStuff(){
        //do stuff 
    }
} 

class FooBar extends Foo {
     void doStuff(){
         super.doStuff();
         //do more stuff
     }
}

我想在 Angular 上做同样的事情-一些

myApp.controller('FooCtrl', function($scope){

    $scope.doStuff = function(){
         //do stuff
     }
}).controller('FooBarCtrl', function($scope){
   angular.extend(this, $controller('FooCtrl', {$scope: $scope}));

   $scope.doStuff = function(){
          // ??? <- INSERT ANSWER HERE  
         //do more stuff
     }
}

最佳答案

我不推荐这种模式,但作为问题的答案,这里有一种方法可以做到:

myApp.controller('FooCtrl', function($scope){

    $scope.doStuff = function(){
         //do stuff
     }
}).controller('FooBarCtrl', function($scope){
   angular.extend(this, $controller('FooCtrl', {$scope: $scope}));
   //extend the scope
   var super = angular.extend({}, $scope);
   $scope.doStuff = function(){
          // ??? <- INSERT ANSWER HERE  
         //do more stuff
         //call the "superclass" methods
         if(super.doStuff){
            super.doStuff();
         }
   }
}

废话,我想你可以编写一个帮助服务,允许你使用对父类(super class)实现的引用来覆盖属性,以使其更清晰。也许通过覆盖“这个”。像这样的东西:

$scope.doStuff = $override($scope.doStuff, function() {

    this();  //calls the original doStuff function
});

.factory('$override', function(){

    return function(method, func){
        return function(){
            return func.apply(method, arguments);
        };
    };
});

关于javascript - Angular Controller 继承/覆盖 "superclass"方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30250201/

相关文章:

c# - User类继承IdentityUser;如何处理多重继承的需要?

Java继承-调用父类(super class)方法

javascript - 如何在 <area> 上添加边框?

javascript - 获取错误 : shuffle(. ..) 在 angularJS 中未定义

java - 覆盖父类的List类型以避免调用方法时进行强制转换

javascript - 在 AngularJS 的另一个 Controller 中更新变量

javascript - 创建通用函数来关闭模态 angularjs

javascript - jQueryPlugin : return this vs return this. 每个()

Javascript 文件在 Wordpress 中无法正常运行,并且在 Functions.php 中进行了正确的排队

javascript - 如果抛出异常,为什么 GruntJS 不中断执行?