更改自己对象中函数内对象的属性

时间:2016-09-06 17:16:00

标签: javascript object properties scope this

我创建了一个对象并为其设置了一些函数,我的问题是,我可以在我附加到它的函数中更改此对象的属性值吗?

这是我的代码:

    var service = new Object();
    service.login = login;
    service.isUserAuthenticated = false;

    function login(userName, password, successCallback) {
        var requestBody = 'grant_type=password&username=' + userName + '&password=' + password;
        $http.post($rootScope.baseUrl + 'token', requestBody)
            .then(
            function (response) {
                isUserAuthenticated = true;
                successCallback(response);
            },
            function (response) {
                console.log(response);
            })
    }

我想在用户登录系统时更改isUserAuthenticated的值,是否可以在此登录功能中使用?

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

当您将login绑定到service时,this(如果在login函数的正文中使用)将引用service执行login期间的对象。但是,在login函数内定义的后续回调中,作为参数传递给.then(),执行回调后,this将不再引用服务对象,因此您需要将bind服务作为回调的(this)上下文,或者将其存储在闭包中。因此,您可以重写login函数:

// binding 'this' to the service
function login(userName, password, successCallback) {
    var requestBody = 'grant_type=password&username=' + userName + '&password=' + password;
    $http.post($rootScope.baseUrl + 'token', requestBody)
        .then(function (response) {
            this.isUserAuthenticated = true;
            successCallback(response);
        }.bind(this),
        function (response) {
            console.log(response);
        });
}

或者:

// storing the service as a closure
function login(userName, password, successCallback) {
    var requestBody = 'grant_type=password&username=' + userName + '&password=' + password;
    var self = this;
    $http.post($rootScope.baseUrl + 'token', requestBody)
        .then(
        function (response) {
            self.isUserAuthenticated = true;
            successCallback(response);
        },
        function (response) {
            console.log(response);
        });
}

在您的情况下,后者不是绝对必要的,因为您已经将服务存储为在login函数之外声明的变量,并且可以简单地将true分配给{ {1}}。

此外,如果您使用的是ES6,那么您作为回调传递给service.isAuthenticated的函数文字(即function() { //... })可以使用胖箭头表示法编写,并且上下文绑定将是自动执行:

.then()
相关问题