现有函数作为Array.forEach的回调函数

joh*_*hni 0 javascript callback angularjs

这段代码的奇怪行为:

我有一些Angular控制器:

.controller('View1Ctrl', ['$scope', 'CrawlServerExecutor', function ($scope, CrawlServerExecutor) {

    $scope.results = [];

    var showResults = function (results) {
        results.forEach(function (result) {
            $scope.results.push(result);
        });
    };
Run Code Online (Sandbox Code Playgroud)

写这样的时候:

    var showResults = function (results) {
        results.forEach($scope.results.push);
    };
Run Code Online (Sandbox Code Playgroud)

我得到这个错误: Error: undefined is not an object为了尝试访问该push函数,我查看$scope.results了调试器内部并且该对象被识别为数组,但由于某种原因,在这种语法中它并没有引用它的push功能.而且我更喜欢这段代码,因为它更优雅.

任何人都知道为什么会这样?

谢谢

Ale*_*tos 5

您需要将数组绑定到函数,因此可以在正确的上下文中调用它(this正确设置).

results.forEach($scope.results.push.bind($scope.results));
Run Code Online (Sandbox Code Playgroud)