通过对返回函数的引用传递对象

Pass object by reference to a returned function

validations = []

isEmpty = (string) ->
    string is '' or string is undefined or string == null

createValidation = (scopeVariable, expected, responseText, inverse) ->
    if inverse == undefined
        inverse = false

    if !inverse
        returningValidation = ->
            if scopeVariable isnt expected
                $scope.response.text = responseText
                $scope.response.class = 'text-danger'
                return false
            true
    else
        returningValidation = ->
            if scopeVariable is expected
                $scope.response.text = responseText
                $scope.response.class = 'text-danger'
                return false
            true

    returningValidation

validateCredentials = ->
    validated = true
    validations.map (validate) ->
        if !validate()
            validated = false
    validated

$scope.register = ->
    if validateCredentials()
        #Account.register $scope.form, (response) ->
            #if response.user_created is true
        $scope.response.text = '...'
        $scope.response.class = 'text-success'

validations.push createValidation $scope.form.termsChecked, true, '...'
validations.push createValidation $scope.form.password, $scope.form.passwordRepeat, '...'

inverse = true
validations.push createValidation $scope.form.password, undefined, '...', inverse
validations.push createValidation $scope.form.password, '', '...', inverse

我有一个 AngularJS 应用程序,我正在尝试创建一个带有表单验证的应用程序。每种验证都创建了一个函数。应该将 $scope.form.input 对象传递给每个输入。但看起来它正在按价值传递。真不知道这种JS闭包是怎么工作的

任何类型的信息都会有所帮助。

在 javascript 中,您不能通过引用传递简单类型(字符串、数字、布尔值)。作为替代方案,您可以传递一个函数来获取您正在寻找的值。因此,例如,不是传递 $scope.form.termsChecked,而是传递 returns $scope.form.termsChecked.

的值的函数

这是一个例子,用 JavaScript 写的,因为我的 CoffeeScript 不太好。

createValidation = function(valueProvider, expected, responseText, inverse) {
    // Skipping a bunch of your code for brevity...
    returningValidation = function() {
        var scopeVaraible = valueProvider();
        console.log(scopeVariable);
        // Now do some validation stuff...
    }
    return returningValidation;
}

validations.push(
    createValidation(function() { return $scope.form.termsChecked; }, true, '...');